ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Follow publication

Coroutines with Architecture components

Radheshyam Singh
ProAndroidDev
Published in
5 min readMay 28, 2019

image from here

Google I/O brought various interesting things for Android Developers. One of them is — use of coroutines effectively with architecture components like lifecycle and liveData. In this article we will go through both of them.

1. Coroutines and LiveData:

LiveData is an observable value holder for UI and we are expected to be able to access the value from the main thread. With the release of livedata-2.1.0-alpha1, google provided the interoperability between LiveData and Coroutines.

Let’s begin with an example to see the details. Suppose we want to fetch Employee information either from database or network and want to show the result on UI(Activity or fragment). So we will create a LiveData in viewmodel and add observer to the same in activity or fragment. Let’s start this step by step:

Step 1: Add dependency to app module’s build.gradle

Step 2: Create LiveData into viewmodel and add method to get data from repository (repository will handle either data needed from database or network).

Step 3: Create observer in Activity that observe the liveData value.

Now in IO’19 google has released livedata-2.2.0-alpha01 which introduced a new building block in LiveData. So above code in viewmodel (step 2) will look like:

This makes the code more simple and concise. It will start execution of block automagically when LiveData becomes active. It will also manage when to start/cancel coroutine inside the building block. To set the result to LiveData we can use emit()/emitSource() method.

Let’e see another example where we will discuss the use of emitSource(). Suppose we want to show cached data (from local database) to UI and then we want to hit the remote server for the latest data. So with the help of LiveData and coroutine we can achieve this as:

Add this to your Employee Dao class
Add this to ViewModel class

In the above example we are using the emitSource() that will attach the LiveData from database to our LiveData in viewmodel. Now we are requesting the server for updated data and finally we are updating the local database with the result. Now our UI will also get the latest result since database LiveData is attached to our LiveData with emitSource.

2. Coroutine with viewModel scope

A coroutine can resume itself and in addition to using memory, it can use CPU, it could write a file, it could make a network request that does not need to happen. This will lead to leak which is known as coroutine leak.

To help us deal with coroutine leak, Kotlin introduced an idea to coroutine scopes — a way of keeping track of our coroutines. All coroutines must run in a scope and a scope gets the ability to cancel all of the coroutines inside of it and also handles get uncaught exceptions to make sure you never leak a Coroutine.

If we are running coroutines in a ViewModel and our ViewModel is getting destroyed, all the asynchronous work that it might be doing must be stopped. Otherwise, you’ll waste resources and potentially leaking memory. This can be achieved as:

To handle coroutine scope automatically in viewModel, android introduced extension property of viewModel as viewModel.ViewModelScope in AndroidX lifecycle v2.1.0.

ViewModelScope:

A viewModelScope is defined for each viewModel in our app. It is bound to ViewModel’s lifecycle and will handle cancellation of all coroutines, when the ViewModel onClear() is called.

So we can achieve the same functionality as above with concise code as:

3. Coroutines with LifecycleScope

We have read about viewModelScope which ensures that a long task, running in viewModelScope will be cancelled once viewModel will not be live. That ensures there will not be any memory leak due to the task which run in viewModelScope.

Suppose there is a requirement to show Snackbar after 2 second of clicking on a button. Here we can’t use viewModelScope because viewModel may exist beyond the UI lifecycle. So to tackle this type of situations AndroidX lifecycle v2.2.0. introduced LifecycleScope. LifecycleScope is very tightly coupled with UI and it works best in situations like that. All the coroutines in that scope will be canceled when the Lifecycle is destroyed.

activity.lifecycleScope.launch {
// scope bound to Activity Lifecycle
}
fragment.lifecycleScope.launch {
// scope bound to Fragment Lifecycle
}
fragment.viewLifecycleOwner.launch{
// scope bound to Fragment View
}

Let’s discuss our above scenario to show SnackBar after 2 second of button click. Below are the way to handle this

Here we have started a coroutine on main dispatcher to show SnackBar after 2 second. If user will press back within 2 second to navigate back from this screen then this will lead to the crash of application.

Now let’s try this by lifecycleScope.

Here after pressing back button within 2 second there will not be any crash because the task to show SnackBar will get cancelled as soon as this fragment gets destroyed. You can find a working sample here.

Conclusion:

In this article we have gone through viewModelScope, lifecycleScopes and LiveData building block. If you are using android architecture components then you should try out these features. Code for these demo is here.

I hope this explanation has given some insights on use of coroutines with architecture components. Also it will allow you to adopt an approach that works during your LiveData, ViewModel and LifeCycle design.

I’m looking forward to writing more on other topics. 👏 clap 👏 if you learnt at-least one thing & share if you feel the content deserves. Give Feedback, Comment or start a discussion. Feel free to correct mistakes.

Find me!

LinkedIn: www.linkedin.com/in/radheshyam-singh-9a2747a9

Happy coding!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Published in ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Responses (10)

Write a response