Use ViewModelScope For Less Boilerplate Code With Coroutines

Amit Shekhar
May 13, 2019 · 2 min read
Image for post
Image for post

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.

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.

Our community publishes stories worth reading on Android…

Amit Shekhar

Written by

MindOrks

MindOrks

Amit Shekhar

Written by

Working with the smartest people in the world to change the way developers learn. Our two EdTech products: MindOrks and AfterAcademy | https://amitshekhar.me

MindOrks

Our community publishes stories worth reading on Android Development

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