Fannie  Zemlak

Fannie Zemlak

1595931360

Coroutines, Retrofit, and a nice way to handle Responses

Before we start, I assume the reader has knowledge and base concepts of KotlinCoroutinesReactiveX, and Android App Architecture.


One-time fetch operation

With coroutines becoming more popular theses days I’ve decided to update my ViewModel-Repository-DataSource communication logic and change it from ReactiveX to Coroutines. There’s nothing wrong with Rx, actually, Kotlin has data streams - checkout Flow and Channel -, but I completely agree with what Daniel Lew said in his Grokking Coroutines talk:

“…concurrency doesn’t have anything to do with streams of data.”

How many of us have implemented a scenario where _“one-time fetch operation” is _used to return data, complete, or throw an error:

//ViewModel
	fun getEmoji(showLoading: Boolean) {
	    repo.emojiList()
	        ...
	        .observeOn(AndroidSchedulers.mainThread())
	        .subscribe(
	            { list -> ... },
	            { error -> ... }
	        ).addToComposite()
	}

	//Repository
	fun emojiList(): Single<List<Emoji>> {
	    service.emojiList().map { ... }
	}

	//Service
	fun emojiList(): Single<List<EmojiRemote>> {
	    return api.emojiList().compose(networkMapTransform())
	}

Architecture based on stream events

What we really intend for is an asynchronous task that will fetch data, maybe perform some operations and finally notify us when ready. We don’t need a Single or Completable for that.

Bearing in mind that I have already successfully implemented this approach in a few projects, I decided to write about it.


Asynchronous architecture

First, let’s draw our architecture. We’ll have a BaseService responsible for handling network calls, successes and errors. **ChildServices **will extend BaseService. Our **Repository **will communicate with ChildServices and manage all the information before returning it back to the **ViewModel **with a Response mapped to ViewModel’s world.

abstract class BaseService(...) {

	    protected suspend fun <T : Any> apiCall(call: suspend () -> Response<T>): Result<T> {
	        val response: Response<T>
	        try {
	            response = call.invoke()
	        } catch (t: Throwable) {
	            return Result.Error(mapNetworkThrowable(t))
	        }

	        if (!response.isSuccessful) {
	            val responseErrorBody = response.errorBody()
	            if (responseErrorBody != null) {
	                try {
	                    //try to parse to a custom ErrorObject
	                    ...
	                    return Result.Error(mapApiThrowable(errorResponse.title, errorResponse.statusCode ?: response.code()))                    
	                } catch (e: Throwable) {
	                    Timber.i(e)
	                }
	            }
	            return Result.Error(mapHttpThrowable(Exception(), response.code(), response.message()))
	        } else {
	            if (response.body() == null) {
	                return Result.Error(mapApiThrowable("", 0))
	            }
	        }
	        return Result.Success(response.body()!!)
	    }

	    private fun mapNetworkThrowable(throwable: Throwable): Exception {
	        //HttpException, SocketTimeoutException, etc...
	    }

	    protected fun mapHttpThrowable(throwable: Throwable, code: Int, message: String): Exception {
	        //InvalidGrantException, ForbiddenException, etc...
	    }

	    protected open fun mapApiThrowable(message: String, code: Int): Exception {
	        //overridden by child service
	    }
	}

#kotlin-coroutines #retrofit #sealed-classes #reactive-programming #android

What is GEEK

Buddha Community

Coroutines, Retrofit, and a nice way to handle Responses
Fannie  Zemlak

Fannie Zemlak

1595931360

Coroutines, Retrofit, and a nice way to handle Responses

Before we start, I assume the reader has knowledge and base concepts of KotlinCoroutinesReactiveX, and Android App Architecture.


One-time fetch operation

With coroutines becoming more popular theses days I’ve decided to update my ViewModel-Repository-DataSource communication logic and change it from ReactiveX to Coroutines. There’s nothing wrong with Rx, actually, Kotlin has data streams - checkout Flow and Channel -, but I completely agree with what Daniel Lew said in his Grokking Coroutines talk:

“…concurrency doesn’t have anything to do with streams of data.”

How many of us have implemented a scenario where _“one-time fetch operation” is _used to return data, complete, or throw an error:

//ViewModel
	fun getEmoji(showLoading: Boolean) {
	    repo.emojiList()
	        ...
	        .observeOn(AndroidSchedulers.mainThread())
	        .subscribe(
	            { list -> ... },
	            { error -> ... }
	        ).addToComposite()
	}

	//Repository
	fun emojiList(): Single<List<Emoji>> {
	    service.emojiList().map { ... }
	}

	//Service
	fun emojiList(): Single<List<EmojiRemote>> {
	    return api.emojiList().compose(networkMapTransform())
	}

Architecture based on stream events

What we really intend for is an asynchronous task that will fetch data, maybe perform some operations and finally notify us when ready. We don’t need a Single or Completable for that.

Bearing in mind that I have already successfully implemented this approach in a few projects, I decided to write about it.


Asynchronous architecture

First, let’s draw our architecture. We’ll have a BaseService responsible for handling network calls, successes and errors. **ChildServices **will extend BaseService. Our **Repository **will communicate with ChildServices and manage all the information before returning it back to the **ViewModel **with a Response mapped to ViewModel’s world.

abstract class BaseService(...) {

	    protected suspend fun <T : Any> apiCall(call: suspend () -> Response<T>): Result<T> {
	        val response: Response<T>
	        try {
	            response = call.invoke()
	        } catch (t: Throwable) {
	            return Result.Error(mapNetworkThrowable(t))
	        }

	        if (!response.isSuccessful) {
	            val responseErrorBody = response.errorBody()
	            if (responseErrorBody != null) {
	                try {
	                    //try to parse to a custom ErrorObject
	                    ...
	                    return Result.Error(mapApiThrowable(errorResponse.title, errorResponse.statusCode ?: response.code()))                    
	                } catch (e: Throwable) {
	                    Timber.i(e)
	                }
	            }
	            return Result.Error(mapHttpThrowable(Exception(), response.code(), response.message()))
	        } else {
	            if (response.body() == null) {
	                return Result.Error(mapApiThrowable("", 0))
	            }
	        }
	        return Result.Success(response.body()!!)
	    }

	    private fun mapNetworkThrowable(throwable: Throwable): Exception {
	        //HttpException, SocketTimeoutException, etc...
	    }

	    protected fun mapHttpThrowable(throwable: Throwable, code: Int, message: String): Exception {
	        //InvalidGrantException, ForbiddenException, etc...
	    }

	    protected open fun mapApiThrowable(message: String, code: Int): Exception {
	        //overridden by child service
	    }
	}

#kotlin-coroutines #retrofit #sealed-classes #reactive-programming #android

Mobile Responsive Web Design

Mobile responsive website design will make your site mobile-friendly, improve the way it looks on devices with both large and small screens, increase the amount of time that visitors spend on your site and help you improve your rankings in search engines.

Contact now to Get the best website design services at a reasonable price from Skenix Infotech.

#responsive web design company in india #responsive web design services #hire web designer #mobile responsive design #responsive web design #mobile web design

10 Responsive Web Design Challenges And Their Solution

Even though your website works perfectly on a desktop, doesn’t mean it’ll render perfectly on mobile or tablets as well. With the plethora of devices available, you’re bound to miss out a few crucial ones, and hurt your users’ experience. Optimising your website for every single device seems like a daunting task, but what if i told you that you don’t have to do it!

All you need to do is make sure that your website has responsive web design, i.e your content adjusts to different devices automatically, and you’re good to go. But, it is easier said than done, even while making your website responsive, you’re bound to face certain challenges on the way.

In this article on responsive web design, I’ll explore the challenges faced with responsive web design to ease out the process for you. Also, I’ll also explain how to transition to responsive web design and why you should go for it? So, hold on to your seats, coz you’re in for a ride!

What Is Responsive Web Design?

Image for post

responsive design-google

Responsive Web Design is the design approach where you make sure that the web pages automatically adjust to the different view ports they are being accessed on. In simpler terms, it means making web pages that look great on all devices.

While making your website responsive, you have to ensure that all the elements automatically scale in accordance with the screen size and resolution. This makes sure that all the different users accessing your website using different devices gets a seamless user experience.

Why Should You Go for Responsive Web Design?

#responsiveness #responsive-web-design #web-development #responsive-design #web-design

anita maity

anita maity

1621077133

Responsive Footer Design using HTML, CSS & Bootstrap

Hello Readers, welcome to my other blog, today in this blog I’m going to create a Responsive Footer by using HTML & CSS only. Earlier I have shared How to create a Responsive Navigation Menu and now it’s time to create a footer section.

As you can see on the image which is given on the webpage. There are various important topics there like About us, Our services and subscribes, some social media icons, and a contact section for easy connection. I want to tell you that it is fully responsive. Responsive means this program is fit in all screen devices like tablet, small screen laptop, or mobile devices.

Live Demo


#responsive footer html css template #footer design in html #simple footer html css code #simple responsive footer codepen #responsive footer code in html and css #responsive footer html css codepen

Oda  Shields

Oda Shields

1625237940

MVVM Movie App with Coroutine, LiveData, Retrofit 2 & Dagger-Hilt

Source Code: https://github.com/IsaiasCuvula/tv_show_app_details

API Link: https://api.tvmaze.com/

Subscribe for more: https://www.youtube.com/channel/UChCgMnyGKOgEGDvubbjjr6A

Thanks for watching, leave a like, leave a comment…
Don’t forget to subscribe to the channels and click on the bell to activate notifications!

Github ----- https://github.com/IsaiasCuvula
Website ----- https://www.bersyte.com/
Twitter ----- https://twitter.com/ICuvula
Instagram ----- https://www.instagram.com/isaias_cuvula/
My App ---- https://play.google.com/store/apps/details?id=com.bersyte.berlist

#Bersyte #AndroidDev #Kotlin

#mvvm #coroutine #livedata #retrofit 2 & dagger-hilt