Use ViewModelScope For Less Boilerplate Code With Coroutines

As we all are already using Kotlin for our Android app, we have also started using the coroutines to handle the concurrency in the Android application. There is something called Scope in Kotlin Coroutines. Google recently introduced the ViewModelScope in the AndroidX Lifecycle to make your code less boilerplate while using Scope in Kotlin Coroutines. In this blog, we will learn how to use the ViewModelScope for less boilerplate code with coroutines.

Let’s understand the Scope first, then the ViewModelScope.

Scopes in Kotlin Coroutines

Scopes in Kotlin Coroutines are very useful because we need to cancel the background task as soon as the activity is destroyed. Similarly, for the task present in the ViewModel, it should get canceled as soon as the ViewModel is cleared.

If you want to read in detail, I highly recommend reading this article on Mastering Kotlin Coroutines.

Let’s see how we currently achieve the task cancellation. We need to implement the CoroutineScope, attach the Job with the CoroutineContext and cancel the job inside the onCleared function.

class HomeViewModel : ViewModel(), CoroutineScope {

override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job

private val job: Job = SupervisorJob()

override fun onCleared() {
super.onCleared()
job.cancel() // cancel the job
}

fun fetchAndShowUser() {
launch {
val user = fetchUser()
// show user in UI
}
}

suspend fun fetchUser(): User {
return withContext(Dispatchers.Default) {
// fetch user
// return user
}
}
}

There is a lot of boilerplate code which can be removed.

Using the ViewModelScope, we can have a less boilerplate code.

To use viewModelScope, just import the following dependency in your build.gradle file:

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

Then, in your ViewModel,

class HomeViewModel : ViewModel() {

fun fetchAndShowUser() {
viewModelScope.launch {
val user = fetchUser()
// Show User In UI
}
}

suspend fun fetchUser(): User {
return withContext(Dispatchers.Default) {
// fetch user
// return user
}
}
}

Here, no need to implement the CoroutineScope, no need to attach the Job in the CoroutineContext and no need to cancel the job inside the onCleared function.

That’s it. We just need to use the viewModelScope. Hence, less boilerplate code.

This is how ViewModelScope is very useful. That’s it for now. Thanks for your time.

Happy Learning :)

Clap, share if you like it and follow me for the updates.