Luis Munoz
07/08/2019, 4:20 PMZach Klippenstein (he/him) [MOD]
07/08/2019, 5:08 PMdelay
is implemented depends on the dispatcher.
I recommend looking at the actual code, but at a high level, the delay function checks the current context’s dispatcher to see if it implements the Delay
interface. If so, it asks the dispatcher to resume the continuation after the delay, and it’s up to the dispatcher to figure out how to do that (e.g. on Android Main dispatcher it will use postDelayed
). Otherwise, it falls back to using the default dispatcher (which always implements Delay
using its event loop) to resume the continuation.
I believe all the built-in dispatchers (Default
, IO
, runBlocking
) implement delays using something like a heap data structure that sorts scheduled tasks by how far into the future they are, and so if there’s no more work can just sleep until the next-soonest task is ready to run. But I’m not as certain about that implementation, and would again recommend looking at the code.