Should I avoid doing this ``` launch { ...
# coroutines
j
Should I avoid doing this
Copy code
launch {
            launch {}
            launch {}
            launch {}
        }.join()
over this?
Copy code
listOf(
            launch {},
            launch {},
            launch {}
        ).joinAll()
Either way, why? Thanks!
o
the first one will have a bit more overhead since it still needs to do an initial async launch. probably the most kotlin-like way is:
Copy code
coroutineScope {
  launch {}
  launch {}
  launch {}
}
1
☝️ 9
j
oooooo, awesome, thanks!
s
afaik in option 1 you will wait only for outer launch to finish, not for inner launches you HAVE to use
coroutineScope
as in previous answer or option 2
🙏 1
j
What about this? Looks like you're wanting to do parallel ops and join results in the end
Copy code
suspend fun concurrentSum(): Int = coroutineScope {
    val one = async { doSomethingUsefulOne() }
    val two = async { doSomethingUsefulTwo() }
    one.await() + two.await()
}
🙏 1
That'd be what I'd expect if using kx.coroutines
d
If you're waiting for return values. This is not the case here AFAIU
🙏 1
l
@sikri
Copy code
launch {
            launch {}
            launch {}
            launch {}
        }.join()
behaves in the exact same was as
Copy code
coroutineScope {
  launch {}
  launch {}
  launch {}
}
@sikri because of the principle of Structured Concurrency that a parent (outer launch) does not complete before all of its children (inner launches) have completed.
s
indeed, my mistake, i missed the
join
in option 1