Created
June 3, 2023 10:35
-
-
Save omkar-tenkale/d300cad271318172db384faef974e6c3 to your computer and use it in GitHub Desktop.
This file contains 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
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