Skip to content

Instantly share code, notes, and snippets.

@omkar-tenkale
Created June 3, 2023 10:35
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/d300cad271318172db384faef974e6c3 to your computer and use it in GitHub Desktop.
Save omkar-tenkale/d300cad271318172db384faef974e6c3 to your computer and use it in GitHub Desktop.
sealed class Dispatcher {
object Main : Dispatcher()
object Background : Dispatcher()
}
fun launch(dispatcher: Dispatcher, block: suspend () -> Unit) {
//Define a callback
val callback = object : Continuation<Unit> {
override val context = EmptyCoroutineContext
override fun resumeWith(result: Result<Unit>) {}
}
//Create coroutine
val continuation = block.createCoroutineUnintercepted(callback)
//Start coroutine on specified dispatcher
when (dispatcher) {
Dispatcher.Main -> Handler(Looper.getMainLooper()).post {
continuation.resumeWith(Result.success(Unit))
}
Dispatcher.Background -> thread {
continuation.resumeWith(Result.success(Unit))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment