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

jeggy

06/14/2020, 5:23 PM
If I'm creating a bunch of coroutines and doing a lot of work, should I be calling
yield()
every now and then all around in the code, so if any cancelation is requested that all my coroutines will cancel? And if so, how expensive is it to call
yield
?
o

octylFractal

06/14/2020, 5:30 PM
it depends on how urgent it is that they be canceled - additionally, it's probably better to call
ensureActive()
because that won't suspend at all, unlike
yield()
. suspending is not too expensive, but it does stop work for a tiny bit
j

jeggy

06/14/2020, 5:36 PM
So if I would have a loop of 100k and in each iteration I'm doing some work inside a coroutine. Would it make sense to then call
ensureActive
upon each iteration?
o

octylFractal

06/14/2020, 5:42 PM
if you have something that could cancel that work and no other spot that checks for it, yes
👍 1
j

jeggy

06/14/2020, 5:45 PM
I'm building a GraphQL library, so what the exact work is is unknown. But I have some example where I would wrap it with
withTimeout
and then I had some problems with it that it still went on for some minutes after it should have been canceled. So I'm just trying to figure out what's the best way to really cancel the execution.
o

octylFractal

06/14/2020, 5:47 PM
yea, use ensureActive then
j

jeggy

06/14/2020, 5:47 PM
I think I will just call
ensureActive()
each time I'm calling the provided lambda by the user of this library 🙂
Thanks for the help 👍
o

octylFractal

06/14/2020, 5:49 PM
also, is the lambda suspending or blocking?
j

jeggy

06/14/2020, 5:50 PM
suspending
o

octylFractal

06/14/2020, 5:51 PM
j

jeggy

06/14/2020, 5:52 PM
fun resolver(function: suspend (T) -> R)
This is the function I'm exposing from this library. But it could be that the code provided is using some blocking code.
o

octylFractal

06/14/2020, 5:53 PM
I wouldn't worry about it too much
j

jeggy

06/14/2020, 5:54 PM
I will just stick with
ensureActive
, and see how it works with big data sets
5 Views