Retrofit With Kotlin Coroutines

- android kotlin retrofit coroutines

As of version 2.6.0 Retrofit has native support for Kotlin coroutines! This allows us to write intuitive and idiomatic code for making network calls from our Android application.

On many Android projects RxJava has been used in combination with Retrofit to make network calls. In this case a Retrofit interface function would look like,

fun getAll(): Single<PokemonListResult>

We are using the RxJava Single object to handle the asynchronous nature of the network call. Making the call would look like,

    .subscribe(pokemonList -> {
        // TODO handle success
    }, throwable -> {
        // TODO handle error

While this syntax is not particulary complex and learning the basics of RxJava for the use case of network calls is basic, we can make the code a little bit cleaner thanks to Kotlin coroutines! And remove RxJava if we are not using it elsewhere! :)

Using coroutines our interface is now,

suspend fun getAll(): PokemonListResult

By adding the suspend modifier before the function declaration it marks the function as asynchronous. It’s as if our return type is using the Call Retrofit object and returning type Call.

Making the call looks like,

CoroutineScope(Dispatchers.IO).launch {
    val pokemonList = apiService.getAll()
    withContext(Dispatchers.Main) {
        // TODO Update the UI with our pokemonList!

We use a top level coroutine scope, set to use Dispatchers.IO (optimized to perform disk or network I/O outside of the main thread), to contain any of our asynchronous calls. Once our API call completes we then use withContext on the Main thread to do any appropriate UI updates.

We can see our code becomes simplier and reads easier! If you’d like to see a working example please check out a basic Pokedex example that uses Retrofit with coroutines.