Scopes in ViewModels
class MyViewModel : ViewModel() {
/**
* This is the job for all coroutines started by this ViewModel.
* Cancelling this job will cancel all coroutines started by this ViewModel.
*/
private val viewModelJob = SupervisorJob()
/**
* This is the main scope for all coroutines launched by MainViewModel.
* Since we pass viewModelJob, you can cancel all coroutines
* launched by uiScope by calling viewModelJob.cancel()
*/
private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)
/**
* Cancel all coroutines when the ViewModel is cleared
*/
override fun onCleared() {
super.onCleared()
viewModelJob.cancel()
}
/**
* Heavy operation that cannot be done in the Main Thread
*/
fun launchDataLoad() {
uiScope.launch {
sortList() // happens on the background
// Modify UI
}
}
// Move the execution off the main thread using withContext(Dispatchers.Default)
suspend fun sortList() = withContext(Dispatchers.Default) {
// Heavy work
}
}
use viewModelScope
class MyViewModel : ViewModel() {
/**
* Heavy operation that cannot be done in the Main Thread
*/
fun launchDataLoad() {
viewModelScope.launch {
sortList()
// Modify UI
}
}
suspend fun sortList() = withContext(Dispatchers.Default) {
// Heavy work
}
}