I'm trying to use `suspendCoroutine` within a `wit...
# coroutines
j
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
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
I totally missed
suspendCancellableCoroutine
, that works. Thanks
g
Interesting, that actually Thread.sleep is designed to be cancellable, but it requires termination of the thread which now what you want with coroutines
184 Views