What is the proper way to implement suspendCancell...
# coroutines
t
What is the proper way to implement suspendCancellableCoroutine but for coroutine / suspend code?
Copy code
suspend fun doLoad() = suspendCancellableCoroutine<Result> {
        val cancellationSignal = CancellationSignal()
        it.invokeOnCancellation { cancellationSignal.cancel() }
        val result = query.cancellationSignal(cancellationSignal).executeAsync()
        if (cancellationSignal.isCanceled) {
            it.resume(Result.Cancelled)
        } else {
            it.resume(Result.Success(result))
        }
    }
In that example all works if executeAsync is blocking, but if executeAsync is a suspend function this no more works. Since cancellation rely on the cancellation signal how to merge the 2 worlds?
d
if executeAsync is a suspend function why do you need to wrap it in suspendCoroutine?
t
The need is about the cancellation event that I need to signal the cancellationSignal to actually do the cancel. if you don't like the executeAsync() Imagine that I'm using a suspend function to get the query.
d
the main reason to use suspendCoroutine is to turn blocking async code into suspend functions, so I don't see a reason to use it in this case
t
The question is not really about why but about how 😉 I need to call the cancellationSignal.cancel() when the coroutine is cancelled. So the question is how do I intercept that in a coroutine job stack to be able to call it.