Using Retrofit 2 with Kotlin coroutines

Since the release of Retrofit2 version 2.6.0, there has been added native support for coroutines, this helps to achieve better performance and reduces boilerplate significantly. I haven't seen many people adapting to this change, So I hope this article helps you to adapt your app.
In this article I will be using the example of an air quality finding app that I made, the application is written in Kotlin and uses MVVM, so I will show you how to change/implement your repository, view model and the UI controlling activity. Finally I will show you how to handle errors with this new approach.
The main changes that you will need to make is making the coroutine calling functions suspendable, as is required for them to function in their intended manner, i.e by stopping and starting according to the application state.
So in our API interface we make the @GET function a suspend function
Next comes the Repository class which creates the instance of the retrofit service and initiates the API call, our method for this call should be a suspend function as it will later be called through a coroutine.
As you can see the code which was earlier 50–60 lines has been reduced to a very clean single line, as the procedure has been streamlined through the use of a coroutine.
The main thing missing from the getData() method is the error handling callback that is automatically created when a call is enqueued.This error can be handled by wrapping the coroutine in a try/catch block.
Now that our repository is set up we can create a method in the viewModel which uses the liveData builder to create a process on the IO thread.
//viewModel and liveData dependencies for the coroutine to work
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.0"
The emit function emits the changes in the underlying database to the observer variables, in our case which will be located in the MainActivity.
Here we can see the observer observing the value of aqi from the API and updating the UI accordingly.
Thats it! your code has now become significantly cleaner and you have leveraged the power of coroutines, show some support(👏) if this article has helped you, ask me below if you have any questions.
If you want to see a project that uses coroutines and other architecture components extensively, then you can have a look at my wallpaper application - Wallportal on Github.