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

Sam Garfinkel

07/31/2020, 4:56 PM
Can anyone explain why the
doSomething()
in this snippet prevents the outer
run()
loop from continuing? You’ll notice that
"Continuing to run"
is printed after
"doSomething with $hello done"
which is the opposite pattern I’m looking for.
z

Zach Klippenstein (he/him) [MOD]

07/31/2020, 5:00 PM
doSomething uses coroutineScope, which won't return until all its child coroutines have completed.
s

Sam Garfinkel

07/31/2020, 5:01 PM
Is there an alternative function I’m looking for here?
So in other words, to parallelize and loop, I need to move
coroutineScope
into the outer
run()
?
o

octylFractal

07/31/2020, 5:04 PM
if you want to immediately launch, remove
suspend
and
coroutineScope
and make it an extension on
CoroutineScope
instead
yes, you want it outside of the loop
in the case of parallelism, I'd leave the inner part as suspend and just call it inside
async {}
(or launch if you don't need results)
s

Sam Garfinkel

07/31/2020, 5:08 PM
Makes sense, thanks.
z

Zach Klippenstein (he/him) [MOD]

07/31/2020, 5:11 PM
This is purely a matter of style, but in this case I would probably pass the scope in as a regular param instead of a receiver, and name the function
doSomethingIn
. Receiver feels odd to me unless the function is a generic launcher or something, and this convention reads really clearly that this function will launch a coroutine in a given scope. But same idea regardless.
👍 1
s

Sam Garfinkel

07/31/2020, 5:16 PM
@Zach Klippenstein (he/him) [MOD] Agree completely, this was a sanitized toy example of the problem. The actual code follows better code styles
3 Views