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

Jonathan Walsh

08/06/2019, 4:24 PM
I'm trying to use
suspendCoroutine
within a
withTimeout
call, but the timeout doesn't seem to work. Has anyone run into similar issues?
with
Thread.sleep
the timeout looks to just be completely ignored
Copy code
assertFailsWith(TimeoutCancellationException::class) {
            runBlocking {
                // this timeout is ignored
                withTimeout(100) {
                    suspendCoroutine<Boolean> { cont ->
                        Thread.sleep(150)
                        cont.resume(true)
                    }
                }
            }
        }
and with
launch
and
delay
the timeout is still ignored but the original execution never resumes
Copy code
assertFailsWith(TimeoutCancellationException::class) {
            runBlocking {
                withTimeout(100) {
                    suspendCoroutine<Boolean> { cont ->
                        launch {
                            delay(150)
                            cont.resume(true)
                        }
                    }
                }
            }
        }
l

louiscad

08/06/2019, 4:35 PM
Don't use
suspendCoroutine
if you want the function to be cancellable. Use
suspendCancellableCoroutine
instead.
2
Also, blocking code is not cancellable unless it has been designed specifically for that and you integrate it properly.
So don't expect
Thread.sleep
to be cancellable.
j

Jonathan Walsh

08/06/2019, 5:38 PM
I totally missed
suspendCancellableCoroutine
, that works. Thanks
g

gildor

08/06/2019, 11:15 PM
Interesting, that actually Thread.sleep is designed to be cancellable, but it requires termination of the thread which now what you want with coroutines
156 Views