Issue
I have been trying to understand how Kotlin coroutines work and I came across the delay
function.
My understanding of this works is,
delay
suspends the current thread, where the thread, unlikesleep
, does not consume CPU cycles and is freed to execute other tasks.- How this works is that the code after the delay function is captured as a lambda(Continuation) and can be executed after the given time period by a different thread.
- The implementation seems similar to Javascript's execution model, where the
delay
function causes the continuation to be stored on some kind of a task queue and releases the current thread. After the specified time is elapsed, this task is scheduled on an available thread.
Is my understanding correct?
Also, is there a relation between the thread that calls delay
and the thread that executes the code following the call to delay
.
Thanks!
Solution
Yes. Your understanding is correct. The difference between JS and Kotlin is that the task queue that is used to execute the continuation can be customized by the programmer via CoroutineDispatcher
. In general, there is no relation between the thread that calls delay
and the thread where continuation is scheduled for resume. It is determined by two factors:
If the coroutine uses the
Unconfined
dispatcher, then the thread where the continuation is resumed is some system timer thread used internally in the implementation ofdelay
. You can write your own version ofdelay
that resumesUnconfined
continuations on the thread of your choice.If the coroutine uses some confined dispatcher, then it resumes on the thread or a pool of threads defined by that dispatcher. A number of dispatchers are provided out of the box. For example, in Android using the
UI
dispatcher, the coroutine is going to be always resumed on the AndroidUI
thread. In general, in Kotlin/JVM you can take anyExecutor
and convert it toCoroutineDispatcher
usingasCoroutineDispatcher
extension.
Answered By - Roman Elizarov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.