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

SUPERCILEX

10/19/2018, 7:44 AM
What is the purpose of
join
now that the outer scope will wait for all functions launched within to complete?
e

elizarov

10/19/2018, 7:44 AM
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

SUPERCILEX

10/19/2018, 7:47 AM
I thought of that too
But then why not just use
withContext
at that point?
e

elizarov

10/19/2018, 7:51 AM
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

SUPERCILEX

10/19/2018, 7:54 AM
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

elizarov

10/19/2018, 8:00 AM
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

SUPERCILEX

10/19/2018, 8:02 AM
Ahhhhh, finally putting it all together. Thanks so much!!! ❤️
And I've been using coroutines for a year, lol
4 Views