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, unlike sleep
, does not consume CPU cycles and is freed to execute other tasks.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!
delay is a special suspending function. It suspends the coroutine for a specific time. Suspending a coroutine does not block the underlying thread, but allows other coroutines to run and use the underlying thread for their code.
There is no direct way to achieve this in Kotlin, but we can use Java library functions in Kotlin for this purpose since Kotlin is based on Java. We will use the Timer() and schedule() functions to call a function after a delay.
The difference is that delay is a suspend function that won't block the thread, while Thread. sleep() will block the thread.
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 of delay
. You can write your own version of delay
that resumes Unconfined
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 Android UI
thread. In general, in Kotlin/JVM you can take any Executor
and convert it to CoroutineDispatcher
using asCoroutineDispatcher
extension.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With