What is the purpose of coroutine yield()?

https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/yield.html

Yields a thread (or thread pool) of the current coroutine dispatcher
to other coroutines to run. If the coroutine dispatcher does not have
its own thread pool (like Dispatchers.Unconfined) then this function
does nothing, but checks if the coroutine Job was completed. This
suspending function is cancellable. If the Job of the current
coroutine is cancelled or completed when this suspending function is
invoked or while this function is waiting for dispatching, it resumes
with CancellationException.

It accomplishes at least a few things

  1. It temporarily deprioritises the current long running CPU task, giving other tasks a fair opportunity to run.
  2. Checks whether the current job is cancelled, since otherwise in a tight CPU bound loop, the job may not check until the end.
  3. Allows for progress of child jobs, where there is contention because more jobs than threads. This may be important where the current job should adapt based on progress of other jobs.

Leave a Comment