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
voben
10/23/2019, 4:34 PM
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)
}
}
}