``` withTimeoutOrNull(1000) { suspendCancellab...
# coroutines
i
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
Sonar won’t like the (2) 🐿️
i
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
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
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
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