Created
August 3, 2020 14:24
-
-
Save sagar-viradiya/386ec2192ce63faf7188080a801a116c to your computer and use it in GitHub Desktop.
Kotlin coroutines extensions for switching thread easily
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
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