Tuan Kiet
10/23/2019, 8:32 AMsuspendCancellableCoroutine { continuation -> do we need to check anything like isActive or isCancelled before call resumeWith and why?Dominaezzz
10/23/2019, 1:08 PMDominaezzz
10/23/2019, 1:09 PMcontinuation.invokeOnCancellation or something like that.voben
10/23/2019, 4:25 PMresumevoben
10/23/2019, 4:34 PMaddOnCompleteListener 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
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