Yield
For simple check favor ensureActive()
Relationships
- Prefer:ensureActive()
- why: because ensureActive() is lighter.
Notes
The result of ensureActive() and yield() seem similar, but they are very different. The function ensureActive() needs to be called on a CoroutineScope (or CoroutineContext, or Job). All it does is throw an exception if the job is no longer active. It is lighter, so generally it should be preferred. The function yield is a regular top-level suspension function. It does not need any scope, so it can be used in regular suspending functions. Since it does suspension and resuming, other effects might arise, such as thread changing if we use a dispatcher with a pool of threads (more about this in the Dispatchers chapter). yield is more often used just in suspending functions that are CPU intensive or are blocking threads.