Predict the output
What does this print?
fun main() = runBlocking {
val result = withTimeoutOrNull(300) {
delay(1_000)
"loaded"
}
println(result ?: "timed out")
}Hint 1 of 1
Which is longer: the delay or the timeout?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A timed out
Correct. The block is cancelled at 300 ms and withTimeoutOrNull returns null.
Why not the others?
- B loaded. The delay is longer than the timeout.
- C It throws TimeoutCancellationException. That's withTimeout; the OrNull version returns null.
- D It prints nothing and hangs. delay is cancellable, so the timeout ends it.