In the following block which is inside a suspend f...
# coroutines
a
In the following block which is inside a suspend function
Copy code
val job = launch {
    if (slugs.isNotEmpty()) {
        model.locations = withTimeout(10.seconds) {
            locationsRepository.getLocations(slugs)
        }
    }
}

// Do other tasks

job.join() // Wait for timeout or completed job

return@withContext model
The docs for
withTimeout
state that
Runs a given suspending block of code inside a coroutine with the specified timeout and throws a
TimeoutCancellationException
if the timeout was exceeded.
The code that is executing inside the block is cancelled on timeout and the active or next invocation of the cancellable suspending function inside the block throws a
TimeoutCancellationException
.
It is apparent from the docs that my block would be cancelled and an exception is thrown. Would this exception crash the App or would it just cancel the job?
e
TimeoutCancellationException
is a
CancellationException
so it will bubble up and cancel the containing scope as well. but it doesn't cancel the
Job
so you could catch it inside
🙌 1
it may be simpler to use
withTimeoutOrNull
than
try
-
catch
3
🙌 2
s
a
So,
job.join()
will throw a
CancellationException
, which will in turn cancel the parent scope as well. Right?
s
What happens in this case is that the exception from
withTimeout
propagates to the
job
and causes it to terminate with a silent (non-failure-type) cancellation. That doesn't propagate, so the outer scope doesn't see any errors. The
job.join()
won't throw any exception, it'll just resume normally as soon as the timeout expires.
1
a
Thank you @Sam! for the clarification.
s
Like @ephemient said, I probably wouldn't rely on this behaviour. It's confusing and will hopefully be deprecated in future releases.
👍 3