Skip to content

Instantly share code, notes, and snippets.

@dariush-fathie
Last active August 25, 2021 17:05
Show Gist options
  • Save dariush-fathie/6387cc582cdc15281ca38e4d1136efa1 to your computer and use it in GitHub Desktop.
Save dariush-fathie/6387cc582cdc15281ca38e4d1136efa1 to your computer and use it in GitHub Desktop.
ViewModelScope Extensions
class MainViewModel : ViewModel() {
private fun doIoOperation() = onIO {
// do your IO work here
}
private fun heavyCalculation() = onDefault {
// do your calculation here
}
private lateinit var job: Job
private fun cancelPreviousJobAndStartNewOne(){
if (::job.isInitialized){
job.cancel()
}
// new job
job = onIO {
// ....
}
}
}
class MainViewModel : ViewModel() {
init {
viewModelScope.launch {
// code to execute on main
}
viewModelScope.launch(Dispatchers.IO){
// code to execute on IO
}
}
}
inline fun ViewModel.onMain(
crossinline body: suspend CoroutineScope.() -> Unit
): Job {
// by default, Dispatchers.Main is default dispatcher to viewModelScope
return viewModelScope.launch() {
body(this)
}
}
inline fun ViewModel.onMainImmediate(
crossinline body: suspend CoroutineScope.() -> Unit
): Job {
// make sure to read documentation about immediate dispatcher, it can throw Exception!
return viewModelScope.launch(Dispatchers.Main.immediate) {
body(this)
}
}
inline fun ViewModel.onIO(
crossinline body: suspend CoroutineScope.() -> Unit
): Job {
return viewModelScope.launch(Dispatchers.IO) {
body(this)
}
}
inline fun ViewModel.onDefault(
crossinline body: suspend CoroutineScope.() -> Unit
): Job {
return viewModelScope.launch(Dispatchers.Default) {
body(this)
}
}
inline fun ViewModel.onUnconfined(
crossinline body: suspend CoroutineScope.() -> Unit
): Job {
return viewModelScope.launch(Dispatchers.Unconfined) {
body(this)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment