https://kotlinlang.org logo
#coroutines
Title
# coroutines
t

tyjka

08/28/2018, 3:33 AM
Here in guide https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md#cancellation-and-exceptions in the code example delay() is called in a child coroutine, and then the child coroutine is cancelled. If yield() is not called on the parent coroutine then child won’t be canceled. Why calling yield() on parent makes child cancellable, whereas delay() has to be cancellable by default?
v

Vsevolod Tolstopyatov [JB]

08/28/2018, 8:06 AM
If yield() is not called on the parent coroutine then child won’t be canceled
It’s not true. Child will be cancelled anyway. But without
yield
child will be cancelled before it has a chance to start, so “Child is cancelled” will not be printed, because it will not be started (as it’s already cancelled)
t

tyjka

08/28/2018, 1:31 PM
Thanks for the answer. Yes, it’s true, if I put delay(100) instead of yield then I still get “Child is cancelled”. I’ve read this: https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do on yield. Now I get better understanding of what yield does in generators. But can you please explain what yield does exactly in that code example?
v

Vsevolod Tolstopyatov [JB]

08/28/2018, 2:09 PM
It gives the child chance to execute and reach
delay(Long.MAX_VALUE)
call. Note that child is launched in the same context as parent, which is
runBlocking
, so they cannot run concurrently. With yield: 1) Parent launches child 2) Parent invokes
yield
3) Child launches, invokes
delay(Long.MAX_VALUE)
and suspends 4) Parent cancels child, so
delay(Long.MAX_VALUE)
throws an exception,
finally
block executes and “Child is cancelled” is printed Without yield: 1) Parent launches child 2) Parent cancels child 3) Child immediately cancels, so
launch
body is not even executed 4) Parent prints “Parent is not cancelled”
5 Views