Skip to content
DeveloperMemos

Using ViewModelScope in Android

Android, ViewModel, ViewModelScope, Coroutines1 min read

ViewModelScope is a Kotlin extension provided by the Android Architecture Components library. It allows developers to easily manage the lifecycle of coroutines launched within the scope of a ViewModel. This is particularly useful for long-running background tasks that should be cancelled when the ViewModel is destroyed, as it ensures that the coroutines are cancelled and their resources are properly cleaned up.

To use ViewModelScope, you first need to include the following dependency in your build.gradle file:

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

Next, you need to define a ViewModel class that inherits from androidx.lifecycle.ViewModel. Within the ViewModel, you can launch a coroutine using the viewModelScope builder. Here is an example of how to use ViewModelScope to perform a long-running network request:

1class MyViewModel : ViewModel() {
2 private val repository = MyRepository()
3
4 fun performNetworkRequest() {
5 viewModelScope.launch {
6 val result = repository.makeNetworkRequest()
7 // update the UI with the result
8 }
9 }
10}

The coroutine launched with viewModelScope.launch will be cancelled when the ViewModel is destroyed, ensuring that any resources used by the coroutine are properly cleaned up.

It's also possible to specify a Dispatchers.IO dispatcher when launching the coroutine to perform the network request on a background thread. Here's an example of how to do this:

1viewModelScope.launch(Dispatchers.IO) {
2 val result = repository.makeNetworkRequest()
3 withContext(Dispatchers.Main) {
4 // update the UI with the result
5 }
6}

In this example, the network request is performed on a background thread using the Dispatchers.IO dispatcher, and the UI is updated on the main thread using the Dispatchers.Main dispatcher.

ViewModelScope is a convenient way to manage the lifecycle of coroutines within a ViewModel, and it helps to ensure that resources are properly cleaned up when the ViewModel is destroyed. It's a useful tool for performing long-running tasks in the background while maintaining a responsive UI.