ViewModelScope in Android
ViewModelScope is also called as LifeCycle-aware-component.
Usually in our viewModel if we are using Coroutines, we must clear/cancel it onCancelled() method manually.
Let’s say, if we have 20–30 viewModels in our project. It’s unnecessarily doing manually clearing coroutines. Here is the example for Manual one.
class MainActivityViewModel : ViewModel() {
private val job = Job()
//add job to cancel coroutine
private val scope = CoroutineScope(Dispatchers.IO + job) //get user data
fun getUserData() {
scope.launch {
//write code to get data from server
}
}
override fun onCleared() {
super.onCleared()
//use of Job
job.cancel()
}
}
Use of viewModelScope
Here it comes viewModelScope. To avoid boilerplate code it comes on the screen.
ViewModelScope is a CoroutineScope that tied to the ViewModels lifecycle.
Here we are going the change the above code with viewModelScope to understand the login behind it.
To use viewModelScope we need viewModel-ktx library,
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version")
And Here is the edited code from the above code.
class MainActivityViewModel : ViewModel() {
fun getUserData() {
viewModelScope.launch {
//write code to get data from server
}
}
}
Thats it. Hope you clearly understand the viewModelScopes work here.
Happy Coding:)