What is the purpose of `join` now that the outer s...
# coroutines
s
What is the purpose of
join
now that the outer scope will wait for all functions launched within to complete?
e
Sometime you need to join your particular children before doing something else:
Copy code
val subTask = launch { doSomething() } 
// do something else in parallel
subTask.join()
// continue only when subTask completes
// do more stuff
that is fork-join type of programming style (launch == fork)
s
I thought of that too
But then why not just use
withContext
at that point?
e
A what point?
you can also use
coroutineContext
to the same effect:
Copy code
coroutineContext { 
    launch { doSomething() } 
    // do something else in parallel
}
// continue only when subTask completes
// do more stuff
But that is more nesting in code
s
Interesting
Nevermind about with context, o got myself confused
I guess what bothers me about your code sample is that has two different indentations for parallel work which makes things unclear
Wouldn't this be better code?
Copy code
val subTask = async { doSomething() }
val sub2 = async { ... }

awaitAll(subTask, sub2)

// do more stuff
Or is the point that the first
launch
just needs to do some background with and we don't care about a result?
e
Yes. You use
launch
if you need side-effect of some work (like store stuff to DB). You use async if you need result of some work.
s
Ahhhhh, finally putting it all together. Thanks so much!!! ❤️
And I've been using coroutines for a year, lol