in `suspendCancellableCoroutine { continuation -&g...
# coroutines
t
in
suspendCancellableCoroutine { continuation ->
do we need to check anything like
isActive or isCancelled
before call
resumeWith
and why?
d
No not really.
All you have to do is register a hook.
continuation.invokeOnCancellation
or something like that.
v
I think you do, otherwise your synchronous code will continue to run even though the coroutine might have been cancelled. I think its a good idea to perform the check before calling
resume
Say you’re working with Google play api, and you want to use the
addOnCompleteListener
callback with coroutines, so you decide to wrap this in a
suspendCancellableCoroutine
to get the power of coroutines with your callback. If the coroutine gets cancelled, the code in the
addOnCompleteListener
could still be running. Which means once your addOnCompleteListener callback finishes, before calling
resume
on the suspended function, its probably a good idea to check if that coroutine has been cancelled
Copy code
return suspendCancellableCoroutine { cont ->
        addOnCompleteListener {
            val e = exception
            if (e == null) {
                @Suppress("UNCHECKED_CAST")
                if (isCanceled) cont.cancel() else cont.resume(result as T)
            } else {
                cont.resumeWithException(e)
            }
        }
    }
Example source https://github.com/Kotlin/kotlinx.coroutines/blob/master/integration/kotlinx-coroutines-play-services/src/Tasks.kt