Skip to content

Instantly share code, notes, and snippets.

@omkar-tenkale
Created June 3, 2023 11:20
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/fd7e495d342b4fab72c8cd063b05e189 to your computer and use it in GitHub Desktop.
Save omkar-tenkale/fd7e495d342b4fab72c8cd063b05e189 to your computer and use it in GitHub Desktop.
suspend fun <R> withContext(dispatcher: Dispatcher, block: suspend () -> R): R {
return suspendCoroutineUninterceptedOrReturn<R> { cont ->
val callback = object : Continuation<R> {
override val context = dispatcher
override fun resumeWith(result: Result<R>) {
when (cont.context as Dispatcher) {
Dispatcher.Main -> Handler(Looper.getMainLooper()).post {
cont.resumeWith(result)
}
Dispatcher.Background -> thread {
cont.resumeWith(result)
}
}
}
}
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))
}
}
COROUTINE_SUSPENDED
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment