Safe Retrofit calls extension with kotlin Coroutines for Android in 2021 — Part II

Christopher Elias
May 15 · 3 min read
Photo by Fotis Fotopoulos on Unsplash

Hello again 👋, this is the second part of the series. If you haven’t read the first part, I encourage you to do it in order to understand all the things we are going to do now.

Now that we know how do we have to handle exceptions with coroutines, lets code.

1. Set up or project ⚒️

We gonna use Retrofit and coroutines for this, therefore we are going to add the following dependencies to our app (or android/kotlin library) module gradle file

dependencies {  // Current versions at the time
def retrofit_version = "2.9.0"
def coroutines_version = "1.5.0"

implementation "com.squareup.retrofit2:retrofit:$retrofit_version"
implementation "com.squareup.retrofit2:converter-moshi:$retrofit_version"

implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version"
}

2. Parse exceptions ♻️

There are some common exceptions that could happen when executing a network call, such as SocketTimeoutException, SSLHandshakeException, HttpException, etc. but we are not going to send those exceptions directly, instead of that, we are going to transform those exceptions into readable failures! Let’s do it!

First we are going to create or custom failures extending them from the Failure class.

Creation of custom failures

Now that we got our custom failures, it’s time to map the exceptions into them.

Transform exceptions into custom failures. The ResponseError class is just a structure that represents a handled backend failure, something like a 4XX error.

3. Make retrofit call execution thread safe ⛑️

Now that we have our exception parser extension function we can use it to catch and parse any exception that could happen while executing a network call.

Safe retrofit call wrapper

So the above suspend function has some key features that i’m going to explain to you.

  • ioDispatcher — Coroutine Dispatcher which is expected to be a IO Dispatcher for your app and a TestCoroutineDispatcher in your unit tests.
  • adapter — It accepts a JsonAdapter<ResponseError> which an adapter for parse a JSON object into the desired ResponseError data class
  • retrofitCall — A crossinline suspend function that will be the one who takes your service and execute it safety inside the withContext block. If you don’t have experience with inline functions see the following video where Florina Muntenescu explains it
  • toSuccess() & toError() — These are just extension functions that wraps any object into a Either.Success or Either.Error instance.

4. Integrate it all 🧩

Ok, that’s it. You have a safe retrofit call wrapper extension function! And you can use it just like this

The last part where I use the .let {…} it’s just because the actorsService.getActors() returns a ResponseItems<ActorResponse> object. I just use the Either.mapSuccess helper method for extract the result and return a List of ActorsResponse as expected.

So that what’s it… is it? Uhm… kind of. We could add a little bit of customization here by adding a middleware layer! What can a middleware do for us? It could probably check that the cellphone is connected to the internet or you could validate some data, etc.

Let’s implement a middleware for fun. 👉 Go to part 3 for learn how to do it!

Sample project 👇

See you soon 👋

Nerd For Tech

From Confusion to Clarification

Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/. Don’t forget to check out Ask-NFT, a mentorship ecosystem we’ve started

Christopher Elias

Written by

Android Software Engineer | Android Blogger | 1st Place at Apps Up 2020 | Surf passionate

Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/. Don’t forget to check out Ask-NFT, a mentorship ecosystem we’ve started

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store