Skip to content

Instantly share code, notes, and snippets.

@manuelvicnt
Last active January 9, 2023 05:07
Show Gist options
  • Save manuelvicnt/b58b086bb3d41e9aa727cec4107b1555 to your computer and use it in GitHub Desktop.
Save manuelvicnt/b58b086bb3d41e9aa727cec4107b1555 to your computer and use it in GitHub Desktop.
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
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment