Created
June 3, 2023 11:32
-
-
Save omkar-tenkale/721a790ef59b7ba60bb95aa054a12597 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
fun launch(dispatcher: Dispatcher, block: suspend () -> Unit) { | |
val callback = object : Continuation<Unit> { | |
override val context: CoroutineContext = dispatcher | |
override fun resumeWith(result: Result<Unit>) {} | |
} | |
val coroutine = block.createCoroutineUnintercepted(callback) | |
// Duplicate code #1 | |
when (dispatcher) { | |
Dispatcher.Main -> Handler(Looper.getMainLooper()).post { | |
coroutine.resumeWith(Result.success(Unit)) | |
} | |
Dispatcher.Background -> thread { | |
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>) { | |
// Duplicate code #2 | |
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) | |
// Duplicate code #3 | |
when (dispatcher) { | |
Dispatcher.Main -> Handler(Looper.getMainLooper()).post { | |
coroutine.resumeWith(Result.success(Unit)) | |
} | |
Dispatcher.Background -> thread { | |
coroutine.resumeWith(Result.success(Unit)) | |
} | |
} | |
COROUTINE_SUSPENDED | |
} | |
} | |
suspend fun doWork() { | |
suspendCoroutineUninterceptedOrReturn<Unit> { cont -> | |
thread { | |
// Duplicate code #4 | |
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