Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Kotlin's Coroutine extension functions to switch from one context to another one. Supports [Dispatchers.IO], [Dispatchers.Main], [Dispatchers.Default], [Dispatchers.Unconfined].
/**
* Kotlin's Coroutine extension functions to switch from one context to another one.
* Supports [Dispatchers.IO], [Dispatchers.Main], [Dispatchers.Default], [Dispatchers.Unconfined].
*/
suspend inline fun CoroutineScope.toIO(crossinline scope: suspend CoroutineScope.() -> Unit) {
withContext(Dispatchers.IO) { scope.invoke(this) }
}
suspend inline fun CoroutineScope.toMain(crossinline scope: suspend CoroutineScope.() -> Unit) {
withContext(Dispatchers.Main) { scope.invoke(this) }
}
suspend inline fun CoroutineScope.toDefault(crossinline scope: suspend CoroutineScope.() -> Unit) {
withContext(Dispatchers.Default) { scope.invoke(this) }
}
suspend inline fun CoroutineScope.toUnconfined(crossinline scope: suspend CoroutineScope.() -> Unit) {
withContext(Dispatchers.Unconfined) { scope.invoke(this) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment