Skip to content

Instantly share code, notes, and snippets.

@manuelvicnt
Created December 9, 2020 11:37
Show Gist options
  • Save manuelvicnt/dc9492ee1fc0a38f24b40e79eb2fe33e to your computer and use it in GitHub Desktop.
Save manuelvicnt/dc9492ee1fc0a38f24b40e79eb2fe33e to your computer and use it in GitHub Desktop.
suspendCancellableCoroutine
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