Last active
August 25, 2021 17:05
-
-
Save dariush-fathie/6387cc582cdc15281ca38e4d1136efa1 to your computer and use it in GitHub Desktop.
ViewModelScope Extensions
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 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 { | |
// .... | |
} | |
} | |
} |
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 MainViewModel : ViewModel() { | |
init { | |
viewModelScope.launch { | |
// code to execute on main | |
} | |
viewModelScope.launch(Dispatchers.IO){ | |
// code to execute on IO | |
} | |
} | |
} |
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
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