Using Kotlin Coroutines and Retrofit in Android – A Beginner’s Guide

Using Kotlin Coroutines with Retrofit is the new way of Android Networking in 2019. Developers are moving from RxJava to Kotlin Coroutines. One major reason being pretty code and improving the overall android app architecture.

This tutorial assumes that you are familiar with Retrofit and Kotlin in General.

What we are making?

An App that consumes uses below endpoint and shows the quote of the day in TextView. A button is pressed to fetch the request.

https://quotes.rest/qod

The above endpoint returns the following sample response.

{
  "success": {
    "total": 1
  },
  "contents": {
    "quotes": [
      {
        "quote": "The determination to win is the better part of winning.",
        "author": "Daisaku Ikeda",
        "length": "55",
        "tags": [
          "buddhism",
          "determination",
          "doingyourbest",
          "humanism",
          "inspire",
          "winning"
        ],
        "category": "inspire",
        "title": "Inspiring Quote of the day",
        "date": "2019-06-08",
        "id": null
      }
    ],
    "copyright": "2017-19 theysaidso.com"
  }
}

Add the dependencies

Moshi or Gson, Retrofit , and Retrofit Kotlin Coroutine Adapter, Okhttp and Kotlin Coroutine Adapter.

implementation "com.squareup.moshi:moshi-kotlin:1.8.0"
implementation "com.squareup.retrofit2:retrofit:2.5.0"
implementation "com.squareup.retrofit2:converter-moshi:2.5.0"
implementation "com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2"
implementation "com.squareup.okhttp3:okhttp:3.12.0"
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.1"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.0.1"

The Class for Above Response

class QuoteResponse(val contents: Contents)

class Contents(val quotes: List<Quote>)

class Quote(val quote: String,
            val author: String)

I wrote a class to get the only fields I needed. Quote and Author. You can write the class according to your response.

RestService or RetrofitService

import kotlinx.coroutines.Deferred
import retrofit2.Response
import retrofit2.http.GET

interface RestService {
    @GET("/qod")
    fun getPosts(): Deferred<Response<QuoteResponse>>
}

We are using Deferred Non-blocking Value which is a part of Kotlin Coroutines. Deferred value is a Job with a result.

Function that Consumes the endpoint

fun getQuote(){
        val service = RetrofitFactory.makeRetrofitService()
        CoroutineScope(Dispatchers.IO).launch {
            val request = service.getPosts()
            try {
                val response = request.await()
                withContext(Dispatchers.Main) {
                    if (response.isSuccessful) {
                        response.body()?.let {
                            textView!!.text = it.contents.quotes.get(0).quote + " by " + it.contents.quotes.get(0).author
                        }
                    } else {
                        Log.i("REQUEST","There was a error with code ${response.code()}")
                    }
                }
            } catch (e: HttpException) {
                Log.e("REQUEST", "${e.message}")
            } catch (e: Throwable) {
                Log.e("REQUEST", "Something went wrong")
            }
        }
    }
button.setOnClickListener {
            getQuote()
        }

The await function waits for result without blocking the thread. So the request is fetched in background and the textview is set in main foreground thread.

This was a basic guide to using Retrofit with Kotlin Coroutines. Feel free to share the post with other android developers. And keep coming back for more.

Join India's Largest Code Learning Community on Uphub.io Get it on Google Play
Sharing options: