Skip to content

Instantly share code, notes, and snippets.

@rommansabbir
Created February 17, 2022 05:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rommansabbir/0ccce0ffae01c26022e3f0804dda041e to your computer and use it in GitHub Desktop.
Save rommansabbir/0ccce0ffae01c26022e3f0804dda041e to your computer and use it in GitHub Desktop.
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