Hi! I need to run two `Job`s simultaneously, how w...
# coroutines
g
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
job1 = launch { code block.. } job2 = launch { codeblock..}
o
if you need to wait for them use
join
, not sure if there's
joinAll
s
listOf(launch { }, launch { }).joinAll()
g
@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
no, that's wrong, they run independently regardless of
join
call
launch
starts the coroutine, unless you add
CoroutineStart.LAZY
l
join suspends so that it doesn't go to next code statement until that job completes
g
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
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.