Illustration by Virginia Poltrack

Easy Coroutines in Android: viewModelScope

Cancelling coroutines when they are no longer needed can be a task easy to forget, it’s monotonous work and adds a lot of boilerplate code. viewModelScope contributes to structured concurrency by adding an extension property to the ViewModel class that automatically cancels its child coroutines when the ViewModel is destroyed.

Disclaimer: viewModelScope will be introduced in the AndroidX Lifecycle v2.1.0 which is currently in alpha. As it is in alpha, the API’s may change and there could be bugs. If you find one, please, report it here.

Scopes in ViewModels

A CoroutineScope keeps track of all coroutines it creates. Therefore, if you cancel a scope, you cancel all coroutines it created. This is particularly important if you’re running coroutines in a ViewModel. If your 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. If you consider that certain asynchronous work should persist after ViewModel destruction, it is because it should be done in a lower layer of your app’s architecture.

Add a CoroutineScope to your ViewModel by creating a new scope with a SupervisorJob that you cancel in the onCleared() method. The coroutines created with that scope will live as long as the ViewModel is being used. See following code:

The heavy work happening in the background will be cancelled if the ViewModel gets destroyed because the coroutine was started by that particular uiScope.

But that’s a lot of code to be included in every ViewModel, right? viewModelScope comes to simplify all this.

viewModelScope means less boilerplate code

AndroidX lifecycle v2.1.0 introduced the extension property viewModelScope to the ViewModel class. It manages the coroutines in the same way we were doing in the previous section. That code is cut down to this:

All the CoroutineScope setup and cancellation is done for us. To use it, import the following dependency in your build.gradle file:

implementation “androidx.lifecycle.lifecycle-viewmodel-ktx$lifecycle_version”

Let’s take a look at what’s happening under the hood.

Digging into viewModelScope

The code is publicly available in AOSP. viewModelScope is implemented as follows:

The ViewModel class has a ConcurrentHashSet attribute where it can store any kind of object. The CoroutineScope is stored there. If we take a look at the code, the method getTag(JOB_KEY) tries to retrieve the scope from there. If it doesn’t exist, then it creates a new CoroutineScope the same way we did before and adds the tag to the bag.

When the ViewModel is cleared, it executes the method clear() before calling the onCleared() method that we would’ve had to override otherwise. In the clear() method the ViewModel cancels the Job of the viewModelScope. The full ViewModel code is also available but we are just focusing on the parts we are interested in:

The method goes through all the items in the bag and calls closeWithRuntimeException that checks if the object is of type Closeable and if so, closes it. In order for the ViewModel to close the scope, it needs to implement the Closeable interface. That’s why viewModelScope is of type CloseableCoroutineScope that extends CoroutineScope overriding the coroutineContext and implements the Closeable interface.

Dispatchers.Main as default

Dispatchers.Main is set as the default CoroutineDispatcher for viewModelScope.

val scope = CloseableCoroutineScope(SupervisorJob() + Dispatchers.Main)

Dispatchers.Main is a natural fit for this case since ViewModel is a concept related to UI that is often involved in updating it so launching on another dispatcher will introduce at least 2 extra thread switches. Considering that suspend functions will do their own thread confinement properly, going with other Dispatchers wouldn’t be an option since we’d be making an assumption of what the ViewModel is doing.

Unit Testing viewModelScope

Dispatchers.Main uses the Android Looper.getMainLooper() method to run code in the UI thread. That method is available in Instrumented Android tests but not in Unit tests.

Use the org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutines_version library to replace the Main Dispatcher by calling Dispatchers.setMain with a single threaded executor. Don’t use Dispatchers.Unconfined, it will break all assumptions and timings for code that does use Dispatchers.Main. Since a unit test should run well in isolation and without any side effects, you should call Dispatchers.resetMain() and clean up the executor when the test finishes running.

You can use this JUnitRule with that logic to simplify your code:

Now, you can use it in your Unit Tests.

Notice that this is likely to change. There is an effort to integrate TestCoroutineContext with structured concurrency. For more information, take a look at the issue here.

If you are using architecture components, ViewModel and coroutines, use viewModelScope to let the framework manage its lifecycle for you. It’s a no brainer!

The Coroutines codelab has been already updated to use it. Check it out to find out more about Coroutines and how to use them in an Android app.