Skip to content

Instantly share code, notes, and snippets.

@sagar-viradiya
Created August 3, 2020 14:24
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 sagar-viradiya/386ec2192ce63faf7188080a801a116c to your computer and use it in GitHub Desktop.
Save sagar-viradiya/386ec2192ce63faf7188080a801a116c to your computer and use it in GitHub Desktop.
Kotlin coroutines extensions for switching thread easily
suspend inline fun <T> runOnDefault(crossinline task: suspend () -> T): T {
return withContext(Dispatchers.Default) {
task.invoke()
}
}
suspend inline fun <T> runOnIO(crossinline task: suspend () -> T): T {
return withContext(Dispatchers.IO) {
task.invoke()
}
}
// Usage
runOnDefault {
// Call your suspending fuction here or do computationally heavy task here.
}
runOnIO {
// Do IO related tasks here such as Network call or DB call.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment