Created
December 9, 2020 11:37
-
-
Save manuelvicnt/dc9492ee1fc0a38f24b40e79eb2fe33e to your computer and use it in GitHub Desktop.
suspendCancellableCoroutine
This file contains hidden or 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
public suspend inline fun <T> suspendCancellableCoroutine( | |
crossinline block: (CancellableContinuation<T>) -> Unit | |
): T = | |
// Get the Continuation object of the coroutine that it's running this suspend function | |
suspendCoroutineUninterceptedOrReturn { uCont -> | |
// Take over the control of the coroutine. The Continuation's been | |
// intercepted and it follows the CancellableContinuationImpl lifecycle now | |
val cancellable = CancellableContinuationImpl(uCont.intercepted(), ...) | |
/* ... */ | |
// Call block of code with the cancellable continuation | |
block(cancellable) | |
// Either suspend the coroutine and wait for the Continuation to be resumed | |
// manually in `block` or return a result if `block` has finished executing | |
cancellable.getResult() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment