Anyone can an article that deep dives into delays,...
# coroutines
l
Anyone can an article that deep dives into delays, ticker, and other timing related functions with coroutines. Not sure how efficient they are. I know they don't block a thread but how do they know when the delay is over and put you back on the same thread especially when you have many and maybe that thread is now busy? Does it have some sort of event loop that keeps checking the current time with a list of functions that are suspend?
z
I don’t know about any articles covering this, but to answer your question: how
delay
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.