Hello! I have a question. In official kDoc for `su...
# coroutines
m
Hello! I have a question. In official kDoc for
suspendCancellableCoroutine
there is an example of usage with callback (example in 🧵). Will
incokeOnCancellation
be called only when coroutine is cancelled? Or does calling
resumeWithException
also invokes the
incokeOnCancellation
block?
Copy code
suspend fun awaitCallback(): T = suspendCancellableCoroutine { continuation ->
    val callback = object : Callback {
        override fun onCompleted(value: T) {
            continuation.resume(value)
        }

        override fun onApiError(cause: Throwable) {
            continuation.resumeWithException(cause)
        }

    }

    api.register(callback)

    continuation.invokeOnCancellation { api.unregister(callback) }
}
b
From invokeOnCancellation method: > Registers a handler to be synchronously invoked on cancellation (regular or exceptional) of this continuation. When the continuation is already cancelled, the handler is immediately invoked with the cancellation exception. Otherwise, the handler will be invoked as soon as this continuation is cancelled.
The
CancellableContinuation
object used by
suspendCancellableCoroutine
also has a
resume()
method that takes both the value you want to resume with, as well as a lambda to run if the value was cancelled when the value was not used. https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-cancellable-continuation/#499398008%2FFu[…]ns%2F1975948010