https://kotlinlang.org logo
Title
j

Justin

07/25/2020, 12:35 AM
Should I avoid doing this
launch {
            launch {}
            launch {}
            launch {}
        }.join()
over this?
listOf(
            launch {},
            launch {},
            launch {}
        ).joinAll()
Either way, why? Thanks!
o

octylFractal

07/25/2020, 12:37 AM
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:
coroutineScope {
  launch {}
  launch {}
  launch {}
}
1
☝️ 9
j

Justin

07/25/2020, 12:37 AM
oooooo, awesome, thanks!
s

sikri

07/25/2020, 2:07 PM
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

Jorge Castillo

07/25/2020, 5:23 PM
What about this? Looks like you're wanting to do parallel ops and join results in the end
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

dekans

07/25/2020, 5:50 PM
If you're waiting for return values. This is not the case here AFAIU
🙏 1
l

Lukas Lechner

07/29/2020, 2:14 PM
@sikri
launch {
            launch {}
            launch {}
            launch {}
        }.join()
behaves in the exact same was as
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

sikri

07/29/2020, 3:42 PM
indeed, my mistake, i missed the
join
in option 1