Last active
January 9, 2023 05:07
-
-
Save manuelvicnt/b58b086bb3d41e9aa727cec4107b1555 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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