Android Coroutine with retrofit 2.0

Vishvendu

--

Since then Google has introduced Kotlin support for android development we have seen multiple android libraries reaching to the developers to ease the job in development. Following that path Android has introduced coroutine in kotlin 1.3.

As per docs said “A coroutine is a concurrency design pattern that you can use on Android to simplify code that executes asynchronously.

Why we need coroutine?

In the early stage of android development we used to use AsyncTask API to execute asynchronous task which recently got depreciated by android. If you want to know the reasons why android depreciated AsyncTask you can go to this to know more about it.

So due to all those memory leaks, performance issues few people started using RxJava for the asynchronous programming but since the RxJava had a very steep learning curve android team decided to launch coroutine with the kotlin 1.3 .

Coroutine with Retrofit 2.0

In this post I will explain you coroutine with the MVVM(Model-view-viewModel) design pattern and we will fetch some data using TMDBApi from the server with the help of retrofit.

How to hide your API key in the Version Control ?

Hiding API key is very important in any android application and there are certainly many ways to achieve that but here I am going to tell how you can achieve that by adding your API key into local.properties file.

Add API key into your local.properties file with any name

tmdb_api_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

Then get the access of this key in you build.gradle file

buildTypes.each {
Properties properties = new Properties()
properties.load(project.rootProject.file("local.properties").newDataInputStream())
def tmdbApiKey = properties.getProperty("tmdb_api_key", "")
it.buildConfigField 'String', "TMDB_API_KEY", tmdbApiKey
it.resValue 'string', "api_key", tmdbApiKey
}

After the you need to build your project and your API key is available to you so you can access your API key from anywhere in the code.

BuildConfig.TMDB_API_KEY

lets create the project folder structure with the following ways, you can create the folder structure in many ways you like but this is how I prefer my folder structure for MVVM.

  • model- This folder will keep all your Kotlin data classes.
  • network- It will keep all your network related files (Retrofit..)
  • repository- It will keep all your suspend function which will interact with your server APIs or local database.
  • view- It will keep all the activities, adapters and keeping the logic of observing the LiveData required to show on the UI.
  • viewmodel- It will be the class which will hold the LiveData coming from the repository.

From where should I start my coding for MVVM ?

If you are looking for the flow of code from where to start the code I would suggest first convert all your JSON objects to kotlin data class and keep them in the model folder.

Now lets get started with the second step which is defining the network folder by adding retrofit instance.

After finishing the network instance and by adding the API interface move to the repository folder and add the below logic.

After that you need to create the viewmodel which will hold the livedata coming from the repository and hold it in the MutableLiveData object.

Now lets discuss what is happening inside the viewmodel code. We have taken the reference of repository inside our viewmodel, then we have created the job and with the coroutinescope we pass the job along with the IO operations, By doing this we are making sure that when viewModel is destroyed we can cancel the job and avoid any memory leaks.

Inside the getNowPlayingMoviedataFromrepository function (Sorry for the weirdly long name) we launch our viewModelScope which is running on the IO dispatchers. Now we can initiate the request to the server because we are not anymore on the main thread and we can perform the network operations.

Now switching back from background thread to main thread we have to use withcontext with the Main Dispatcher. You can used Async-await as well but that all depends on your requirement of fetching the data from the server.

Our View(Activity) will be observing the data we are fetching from the server

That’s it.

Kindly feel free for any kind of suggestion for the post. This post is for the beginners who are moving from java to kotlin and finding it difficult to understand the concept of coroutine with the combination of retrofit.

follow the link for the code base for the above description.

Thanks

--

--

Responses (1)