I'm not exactly sure what is the purpose of the yield
function. Can you check this example I have?
I am following an example here.
Here is the code:
val job = launch {
val child = launch {
try {
delay(Long.MAX_VALUE)
} finally {
println("Child is cancelled")
}
}
yield() //why do i need this ???????
println("Cancelling child")
child.cancel()
child.join()
yield()
println("Parent is not cancelled")
}
job.join()
When I comment out the first yield I get the following results:
Cancelling child
Parent is not cancelled
but if I leave the yield as it is I get:
Cancelling child
Child is cancelled
Parent is not cancelled
What does it mean to use yield
here?
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