Upon rerunning the following code, I am getting inconsistencies:
fun main(){
runBlocking{
withTimeoutOrNull(205){
delay(200)
println("Within Timeout")
}
delay(300)
println("Outside")
}
}
This appears to be the case within difference margins of 1-10 milliseconds. The console will sometimes printout both print statements but most often, the last println only gets displayed. Why is this happenning?
withTimeoutOrNull(timeMillis, block)
cancels the block
and returns null if the timeout (timeMillis
) was exceeded.
delay(200)
does not guarantee that delay will be exactly 200 ms, it guarantees that the delay is at least 200 ms.
So in case the actual delay is larger 205 ms, withTimeoutOrNull(205)
cancels the passed code block and println("Within Timeout")
is not executed.
From the delay
's doc:
Delays coroutine for at least the given time without blocking a thread and resumes it after a specified time.
From the withTimeoutOrNull
's doc:
The code that is executing inside the block is cancelled on timeout and the active or next invocation of cancellable suspending function inside the block throws a TimeoutCancellationException.