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

irus

11/15/2018, 3:01 PM
Copy code
withTimeoutOrNull(1000) {
    suspendCancellableCoroutine<Unit> { cont ->
        cont.invokeOnCancellation {
            cont.resumeWithException(CancellationException("Hello!")) // 1
            cont.resumeWithException(RuntimeException("Hello!")) // 2
        }
    }
}
Can't find place in documenation where difference between (1) and (2) described
a

Alexandre

11/15/2018, 3:29 PM
Sonar won’t like the (2) 🐿️
i

irus

11/15/2018, 3:42 PM
Because user shouldn't use RuntimeExceptions directly?
@elizarov Is it okay to resume with
CancellationException
during cancellation? I trying to cancel coroutine and underlying future, and future itself has cancellation handler. So in this handler I normally resume with`CancellationException` (for case when future cancelled by http client).
e

elizarov

11/15/2018, 4:02 PM
You don’t need to resume a coroutine inside
invokeOnCancellation
. When
invokedOnCancellation
block is invoked, the suspended coroutine had been already resumed with
CancellationException
by coroutines machinery.
invokeOnCancellation
is there to notify you that this had happened, so that you can cancel some other work that had been performed.
i

irus

11/15/2018, 4:06 PM
Yes, this is how things should work. But in my case:
Copy code
suspend fun HttpAsyncClient.execute(request: HttpUriRequest): HttpResponse {
    return suspendCancellableCoroutine { cont: CancellableContinuation<HttpResponse> ->
        val callback = object : FutureCallback<HttpResponse> {
            override fun completed(result: HttpResponse) {
                cont.resumeWith(Result.success(result))
            }

            override fun cancelled() {
                cont.resumeWith(Result.failure(FutureCallbackCanceledException(request)))
            }

            override fun failed(ex: Exception) {
                cont.resumeWith(Result.failure(ex))
            }
        }

        val future = this.execute(request, callback)

        cont.cancelFutureOnCancellation(future)
        Unit
    }
}
I have
cancelled
handler, and it's being called when
invokeOnCancellation
handler cancels
future
e

elizarov

11/15/2018, 4:32 PM
See this issue: https://github.com/Kotlin/kotlinx.coroutines/issues/830 It should give you some choices on what you can do.
(you can also subscribe to it to get updates)
1
18 Views