Illustration by Virginia Poltrack

Easy Coroutines in Android: viewModelScope

Manuel Vivo
Mar 19, 2019 · 5 min read

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.

Scopes in ViewModels

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

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 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

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

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.

immediate is used to execute the coroutine immediately without needing to re-dispatch the work to the appropriate thread.

Unit Testing viewModelScope

Use the org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutines_version library to replace the Coroutines Main Dispatcher by calling Dispatchers.setMain(dispatcher: CoroutineDispatcher) with a TestCoroutineDispatcher that is available in org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutines_version. Note that Dispatchers.setMain is only needed if you use viewModelScope or you hardcode Dispatchers.Main in your codebase.

TestCoroutineDispatcher is a dispatcher that gives us control of how coroutines are executed, being able to pause/resume execution and control its virtual clock. It was added as an experimental API in Kotlin Coroutines v1.2.1. You can read more about it in the documentation.

Don’t use Dispatchers.Unconfined as a replacement of Dispatchers.Main, 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.

Testing coroutines using Mockito

Before checking that the interaction with an object happened, we need to make sure that all coroutines launched have finished. Let’s take a look at the following example.

In the test, we call the runBlockingTest method inside the TestCoroutineDispatcher that the rule creates. Since that Dispatcher overrides Dispatchers.Main, MainViewModel will run the coroutine on that Dispatcher too. Calling runBlockingTest will make that coroutine to execute synchronously in the test. Since our verify Mockito call is inside the runBlockingTest block, it will be called after the coroutine finishes and the interaction will have happened at that moment.

For another example, check out how we added this kind of Unit tests to the Kotlin Coroutines codelab in the following PR:

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.

Android Developers

The official Android Developers publication on Medium