Skip to content

Instantly share code, notes, and snippets.

@omkar-tenkale
Last active June 3, 2023 11:42
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/7d3bafb69a5f8594c7da6548def736eb to your computer and use it in GitHub Desktop.
Save omkar-tenkale/7d3bafb69a5f8594c7da6548def736eb to your computer and use it in GitHub Desktop.
// Resumes a coroutine on specified dispatcher
class DispatcherContinuation<T>(
override val context: CoroutineContext,
val continuation: Continuation<T>
) : Continuation<T> {
override fun resumeWith(result: Result<T>) {
when (context as Dispatcher) {
Dispatcher.Main -> Handler(Looper.getMainLooper()).post {
continuation.resumeWith(result)
}
Dispatcher.Background -> thread {
continuation.resumeWith(result)
}
}
}
}
fun launch(dispatcher: Dispatcher, block: suspend () -> Unit) {
val callback = object : Continuation<Unit> {
override val context = dispatcher
override fun resumeWith(result: Result<Unit>) {}
}
val coroutine = block.createCoroutineUnintercepted(callback)
// DispatcherContinuation starts the coroutine on correct thread
DispatcherContinuation(dispatcher, coroutine).resumeWith(Result.success(Unit))
}
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>) {
// DispatcherContinuation resumes previous coroutine on correct thread
DispatcherContinuation(cont.context, cont).resumeWith(result)
}
}
val coroutine = block.createCoroutineUnintercepted(callback)
DispatcherContinuation(dispatcher, 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