Take Kotlin channels for example
for(msg in channel){
// to stuff
yield() // maybe?
}
How do you know if yield is required? I assume that Channels are built in a way that yielding happens automatically behind the scenes in the iterator but I'm not sure. In general, how do you know you need manual yields when using the rest of Kotlin's coroutine library that might do it for you automatically?
In most cases you should not at all need to use yield()
or be concerned with it. Coroutines can switch automatically whenever we get to a suspension point, which usually happens pretty often.
yield()
is needed only if our code does not suspend for prolonged time. That usually means we are performing intensive CPU calculations. In your example receiving from the channel is suspending operation, so you don't need yield()
here.
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