https://kotlinlang.org logo
#coroutines
Title
# coroutines
t

Tolriq

11/30/2018, 8:07 PM
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

Daniel Tam

12/01/2018, 6:12 AM
if executeAsync is a suspend function why do you need to wrap it in suspendCoroutine?
t

Tolriq

12/01/2018, 8:50 AM
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

Daniel Tam

12/01/2018, 2:02 PM
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

Tolriq

12/01/2018, 2:17 PM
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.
4 Views