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

Gabriel Feo

12/09/2019, 6:38 PM
Hi! I need to run two `Job`s simultaneously, how would I do this with coroutines? I understand how to do this when I need return values with
Deferred
and
awaitAll
, but I don't know how I should do this with simple `Job`s
l

Luis Munoz

12/09/2019, 6:39 PM
job1 = launch { code block.. } job2 = launch { codeblock..}
o

octylFractal

12/09/2019, 6:39 PM
if you need to wait for them use
join
, not sure if there's
joinAll
s

serebit

12/09/2019, 6:54 PM
listOf(launch { }, launch { }).joinAll()
g

Gabriel Feo

12/09/2019, 7:10 PM
@Luis Munoz, @octylFractal So I read a bit about
join
. I understand that when launching two `Job`s as above, • if I don't
join
each to the parent coroutine, they will run independently, but the parent only finishes when both children do • if I do
join
each to the parent coroutine, they will run sequentially, job2 runs only after job1 finishes, and still the parent finishes only when both children do
Is that right?
o

octylFractal

12/09/2019, 7:10 PM
no, that's wrong, they run independently regardless of
join
call
launch
starts the coroutine, unless you add
CoroutineStart.LAZY
l

Luis Munoz

12/09/2019, 8:24 PM
join suspends so that it doesn't go to next code statement until that job completes
g

Gabriel Feo

12/09/2019, 8:56 PM
I see. Thanks everyone. So to separate the concepts I was mixing up here: 1. just calling both in sequence would run them synchronously
callSuspendFun1(); callSuspendFun2()
2. launching them separately would make them run simultaneously but with the "parent" coroutine continuing execution independently of the jobs completing 3. using
join
on each
launch
separately would make them run sequentially like case 1 4. using
joinAll
on the two launches would launch them simultaneously, with the "parent" only resuming execution once the two jobs have completed I think I got it now, but I should go over the basics...
👍 2
t

tseisel

12/09/2019, 10:00 PM
5. Wrap your 2
launch
inside a
coroutineScope
block, and execution will resume after both jobs have completed just like 4 (but without having to join). This is better for structured concurrency.
7 Views