How does `delay()` work? A comment in source code...
# coroutines
m
How does
delay()
work? A comment in source code (method
scheduleResumeAfterDelay
) says: This implementation is supposed to use dispatcher's native ability for scheduled execution in its thread(s). It means that the method interacts with the thread scheduler to put the current thread into a wait state for the required interval? (like Thread.sleep() https://www.javamex.com/tutorials/threads/sleep.shtml) Or what kind of native ability are we talking about?
l
It schedules a delayed task which resumes the coroutine with the specified time. On Android, it uses
postDelayed
on
Handler
when using the
UI
coroutine context for example.
m
The implementation depends on the coroutine context? In thread with the event loop we can just skip a few iterations. It's great, but what if there are no event loop?
l
Good question !
s
I figure that threads servicing (dispatching for) coroutine context must implement a Looper (Android term), a ExecutorService (java), etc style dispatching of tasks. Or, in a single-threaded context, just call it all on a single stack-frame.
E.g if you write your own CoroutineContext, you must implement (delayed) scheduling operations (Dispatcher) and/or an EventLoop (e.g for blocking calls).
e
Not really must implement it, but you can. If a scheduler does not implement a method for delaying execution, then a default scheduled executor is used to wait for a specified time. But various UI executors (including Android) indeed provide their own methods for delaying execution
👍🏽 2