Skip to content

Instantly share code, notes, and snippets.

@L-Briand
Created May 3, 2023 18:13
Show Gist options
  • Save L-Briand/11ec973e1ca38762dc554e45b95db162 to your computer and use it in GitHub Desktop.
Save L-Briand/11ec973e1ca38762dc554e45b95db162 to your computer and use it in GitHub Desktop.
import kotlinx.coroutines.*
fun CoroutineScope.onMain(action: suspend CoroutineScope.() -> Unit) =
launch(Dispatchers.Main, block = action)
fun CoroutineScope.onIo(action: suspend CoroutineScope.() -> Unit) =
launch(Dispatchers.IO, block = action)
fun CoroutineScope.onDefault(action: suspend CoroutineScope.() -> Unit) =
launch(Dispatchers.Default, block = action)
fun CoroutineScope.onUnconfined(action: suspend CoroutineScope.() -> Unit) =
launch(Dispatchers.Unconfined, block = action)
fun <T> CoroutineScope.asyncMain(action: suspend CoroutineScope.() -> T) =
async(Dispatchers.Main, block = action)
fun <T> CoroutineScope.asyncIo(action: suspend CoroutineScope.() -> T) =
async(Dispatchers.IO, block = action)
fun <T> CoroutineScope.asyncDefault(action: suspend CoroutineScope.() -> T) =
async(Dispatchers.Default, block = action)
fun <T> CoroutineScope.asyncUnconfined(action: suspend CoroutineScope.() -> T) =
async(Dispatchers.Unconfined, block = action)
suspend fun <T> withMain(action: suspend CoroutineScope.() -> T) =
withContext(Dispatchers.Main, block = action)
suspend fun <T> withIo(action: suspend CoroutineScope.() -> T) =
withContext(Dispatchers.IO, block = action)
suspend fun <T> withDefault(action: suspend CoroutineScope.() -> T) =
withContext(Dispatchers.Default, block = action)
suspend fun <T> withUnconfined(action: suspend CoroutineScope.() -> T) =
withContext(Dispatchers.Unconfined, block = action)
fun <T> blockingMain(action: suspend CoroutineScope.() -> T) = runBlocking { withMain(action) }
fun <T> blockingIo(action: suspend CoroutineScope.() -> T) = runBlocking { withIo(action) }
fun <T> blockingDefault(action: suspend CoroutineScope.() -> T) = runBlocking { withDefault(action) }
fun <T> blockingUnconfined(action: suspend CoroutineScope.() -> T) = runBlocking { withUnconfined(action) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment