Created
June 3, 2023 11:20
-
-
Save omkar-tenkale/b51ffc178e4432c5cef3e5f0447edec6 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
suspend fun withContext(dispatcher: Dispatcher, block: suspend () -> Unit) { | |
// Suspend current coroutine | |
suspendCoroutineUninterceptedOrReturn<Unit> { cont -> | |
// Define completion callback for new coroutine | |
val callback = object : Continuation<Unit> { | |
override val context = EmptyCoroutineContext | |
override fun resumeWith(result: Result<Unit>) { | |
// Resume the previous coroutine | |
when (cont.context as Dispatcher) { | |
Dispatcher.Main -> Handler(Looper.getMainLooper()).post { | |
cont.resumeWith(result) | |
} | |
Dispatcher.Background -> thread { | |
cont.resumeWith(result) | |
} | |
} | |
} | |
} | |
// Create and start the new coroutine | |
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