Is there any benefit of using ```val a = async { …...
# coroutines
c
Is there any benefit of using
Copy code
val a = async { … }
val b = async { … }
joinAll(a, b)
val a2 = a.getCompleted()
val b2 = b.getCompleted()
instead of
Copy code
val a = async { … }
val b = async { … }
val a2 = a.await()
val b2 = b.await()
? I believe they are identical (at least in terms of concurrent execution and cancellation behavior).
k
It’s worth noting that
awaitAll
has a specific implementation that’s not just
forEach { it.await() }
, and that presumably has performance benefits associated with it. https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/common/src/Await.kt#L60-L120
joinAll
is just a forEach loop though
c
Maybe in case of
CoroutineStart.LAZY
? If you use a basic for-loop, they will end up being sequential 🤔 But that's not used in my example, and even then, it wouldn't make a difference
c
Yeah, that's along the lines of what I expected. Doesn't answer my question though.
k
I think it does start to answer it. One of the benefits of the second snippet over the first is that if the first deferred completes exceptionally, it will be thrown before the second deferred is awaited. In a scenario where the second deferred takes longer to complete than the first, you save time by not waiting for it to complete.
c
No? Both snippets are sequential,
joinAll
doesn't have all the things we mentioned that
awaitAll
has.
k
I was originally under the impression that
Deferred.join
wouldn't throw an exceptional result, but it looks like I'm wrong! If that's not the case I don't see a difference between these two.