https://kotlinlang.org logo
Title
s

Stylianos Gakis

09/26/2021, 6:04 PM
A question about doing parallel async work using map. (More in Thread 🧵)
👀 1
I’ve seen a function signature that looks like this
suspend fun <A, B> Iterable<A>.pmap(f: suspend (A) -> B): List<B> = coroutineScope {
    map { async { f(it) } }.awaitAll()
}
However I am curious to understand how this would be different from me doing something like this manually in the call site.
something.map {
    async { f(it) } // f() is suspending
}.awaitAll()
The one difference I see here is that the
pmap
function wraps everything with
coroutineScope
but I don’t think I understand why that is. How does it make it any different and will mine break in some case where one of them throws an exception, is cancelled or something like that?
e

ephemient

09/26/2021, 6:22 PM
1. the function won't work without some coroutine scope either created there or passed in 2. behavior-wise, the first ensures that all these mapped parallel asyncs are cancelled as soon as any one fails, whereas in the second it won't happen until whatever scope your function uses is cancelled (which may be later, in case of a supervisor scope, or never, in case of global scope)
s

Stylianos Gakis

09/26/2021, 6:38 PM
1. For the second case, I do imply that it’s inside a for example
viewModelScope.launch { //here }
so it is part of some scope, if that’s what you meant. 2. I wonder why it is that if one fails they all cancel immediately in the case where they are wrapped with
coroutineScope
. What makes that happen, I am completely lost on this one. How does it being wrapped inside a
coroutineScope
make it behave differently from it being wrapped in a
.launch
scope. Is this some special behaviour of
async
? What and where can I read about this to understand it better?
e

ephemient

09/27/2021, 3:51 AM