Network Calls: Kotlin Coroutine + Retrofit 2

JItesh SUvarna
3 min readJan 15, 2019

--

Photo by Dimon Blr on Unsplash

Concurrency, Consistency, Parallel Processing => multiple names but suggesting the same requirement for simple task for computation of different task all at the same time and ensuring the expected output.

A Little Background

Lets get into the Android Realm, asynchronous code is at the core of the Android Development. Every network request should be on background thread and later the respective response must be handled on the Main/UI thread. This whole operation or monkey business needed good amount of boiler plates to setup and if you have a descent size project this can go havoc in few weeks. Enough of background story, let discussion various ways to achieve the same.

  • AsyncTask — Run short operations in sequence, also can be done concurrently. (Boilerplate code, Tedious cancellation and failure handling)
  • Executors — Running tasks concurrently with fixed thread pool. (No direct access to UI thread, Needs micro managing)
  • Intent service — Run long operations in sequence, handled by a queue. (No direct access to UI thread by default, Tasks are queued)
  • RxJava — Using Observer and Observable for handling stream of data. (Steep learning curve, Mainly a event processing library)

New Kid on the Block: Coroutine

Corountine in Kotlin helps to deal with asynchronous task in a sequential/imperative way. Using coroutine is cheaper than using thread and also the management is way easier/straightforward. Beginning with Kotlin 1.3, coroutines are available in stable version evolving from experimental stage.

We are not gonna cover coroutine in depth in this session. Many blogs explaining them neatly can be found around internet [this blog is inspired from many of them 😜]

Setting up gradle

Add the following dependencies to build.gradle at app level module.

Coroutine returns a future object [a object that holds the values that are populated at a later point in time] called Deferred. This are similar to other techniques for storing value of async operations like Java’s Future or Javascript Promise.

For working with Retrofit, we need special CallAdapter [that returns the values from network calls] provided by Kotlin Coroutine Adapter.

Defining API Interface for Retrofit

We are returning the Deferred object of the User defined type in this case EmployeeListModel.

Configuring Retrofit API

We added addCallAdapterFactory(CoroutineCallAdapterFactory()) for getting the Deferred object, later on which we can perform async operations seamlessly.

Async API Call On Background thread

Using the Dispatchers.IO the api is invoked on a background thread, then we await for the response without using the any callback.

Handling UI updates On Main thread

Using the Dispatchers.Main will render the UI with the response on the UI/Main thread without any further handling.

Conclusion

Using Kotlin coroutine with Retrofit makes the code more readable. Making Asynchronous Code callback free in a very neat concise way. Now as it is available on stable version plus integration with network libraries like Retrofit, managing large Code base will be more trouble-free.

Working example is able on my Github repo.

For in depth overview on Kotlin Coroutines you can refer my talk on basis setup and other implementation on the same.

Source

Any improvements are always welcomed. Thanks!

--

--