uli
03/31/2017, 7:48 AMsuspend fun delay(time: Long, unit: TimeUnit = TimeUnit.MILLISECONDS) {
require(time >= 0) { "Delay time $time cannot be negative" }
if (time <= 0) return // don't delay
Wouldn't it be more comfortable to not have require(time >= 0)
Especially, as the implementation for time < 0 follwos right on the next lineelizarov
03/31/2017, 9:27 AMuli
03/31/2017, 1:42 PMelizarov
03/31/2017, 5:22 PMval deadline = System.currentTimeMillis() + timeout
// later
while (true) {
val current = System.currentTimeMillis()
if (current >= deadline) break
delay(deadline - current)
}
It is easy to accidentally mess this loop (mess break condition for example). In this case, delay throwing exception "saves you" (without exception you may end up with a loop that just eats 100% CPU).uli
03/31/2017, 6:07 PMval deadline = System.currentTimeMillis() + timeout
// later
val current = System.currentTimeMillis()
delay(deadline - current)
elizarov
03/31/2017, 7:24 PMwhile (true) {
// do something
val current = System.currentTimeMillis()
if (current >= deadline) break
delay(deadline - current) // not really -- does not make sense
}
delay
(in particular) with a computed time.uli
04/01/2017, 8:15 PMval deadline = System.currentTimeMillis() + timeout
// do some work here
val current = System.currentTimeMillis()
delay(deadline - current)
I'd rather have high CPU load then an exception which would most likely crash as kotlin does not enforce exception handling. Especially, as the 'some work' might be done before timeout expires on my machine. But not on some random production machine.while (true) {
val deadline = System.currentTimeMillis() + pollInterval
// poll server and process result (e.g. update ui)
val current = System.currentTimeMillis()
delay(deadline - current)
}
If the server happens to be slow at a time, this would cause a crash or require special case handling.
If delay(t) for t <= 0 would just return instead of throwing an exception it would just work.
Or even better, if it would queue the continuation but without delay, it would just work, still be cancelable and not starve other coroutines.