Use ViewModelScope For Less Boilerplate Code With Coroutines

Amit Shekhar
May 13, 2019 · 2 min read

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

Project: Learn Kotlin Coroutines for Android by Examples

Check All Free Android Tutorials By MindOrks.

Happy Learning :)

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

MindOrks

Our community publishes stories worth reading on Android…

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

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