Image for post
Image for post
Illustration by Virginia Poltrack

Easy Coroutines in Android: viewModelScope

Manuel Vivo
Mar 19, 2019 · 4 min read

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.

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:

implementation "androidx.lifecycle.lifecycle-viewmodel-ktx$lifecycle_version"

Digging into viewModelScope

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

Dispatchers.Main as default

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

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

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.

Testing coroutines using Mockito

Do you use Mockito and want to verify that interactions with an object happen? Note that using Mockito’s verify method is not the preferred way to unit test your code. You should check app-specific logic such as an element is present rather than verifying that interactions with an object happen.


Android Developers

The official Android Developers publication on Medium

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store