Skip to content

Instantly share code, notes, and snippets.

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 omkar-tenkale/8e082951aea0f7fab301162579fe99f7 to your computer and use it in GitHub Desktop.
Save omkar-tenkale/8e082951aea0f7fab301162579fe99f7 to your computer and use it in GitHub Desktop.
fun launch(dispatcher: Dispatcher, block: suspend () -> Unit) {
val callback = object : Continuation<Unit> {
// Passing dispatcher as CoroutineContext
override val context: CoroutineContext = dispatcher
override fun resumeWith(result: Result<Unit>) {}
}
val coroutine = block.createCoroutineUnintercepted(callback)
when (dispatcher) {
Dispatcher.Main -> Handler(Looper.getMainLooper()).post {
coroutine.resumeWith(Result.success(Unit))
}
Dispatcher.Background -> thread {
coroutine.resumeWith(Result.success(Unit))
}
}
}
suspend fun doWork() {
suspendCoroutineUninterceptedOrReturn<Unit> { cont ->
thread {
// Retrieve Dispatcher from continuation and resume execution
when (cont.context as Dispatcher) {
Dispatcher.Main -> Handler(Looper.getMainLooper()).post {
cont.resumeWith(Result.success(Unit))
}
Dispatcher.Background -> thread {
cont.resumeWith(Result.success(Unit))
}
}
}
COROUTINE_SUSPENDED
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment