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

acando86

10/11/2018, 5:07 PM
I have a list of ids and for each single id i wanna perform a network request to fetch more data about that id, and return the list of "hydrated" ids.. this is a pretty standard usecase, so far so good. I have a suspend function to fetch the data for a single id, I wanna parallelise the network requests, and it's important for me that the final list is in the same order of the original list (aka, kind of
concatMap
of Rx). Is
awaitAll
order-preserving on lists? if not, what's the best way to be non-blocking on the map while keeping the order of the list?
e

enleur

10/11/2018, 5:13 PM
i suppose you do something like this?
Copy code
val results = requests
   .map { req -> async { doRequest(req) }}
   .awaitAll()
simple test shows that is preserves the order
Copy code
val results = listOf(5,3,2,5,7,1,6)
            .map { async { delay(it * 1000L); it } }
            .awaitAll()

        println(results)
Copy code
[5, 3, 2, 5, 7, 1, 6]
a

acando86

10/11/2018, 5:40 PM
yea, i was using
awaitAll
exactly like that but couldnt find in the documentation whether it was guarantee to be order-preserving or not, and since it's not strictly equivalent to .map {it.await()} i was not that sure about the order. cool , thanks
e

enleur

10/11/2018, 5:42 PM
you should add it do your unit tests in case if something changes in the future 🙂
👍 1
e

elizarov

10/11/2018, 8:53 PM
There is a guarantee on a preserved order. We’ve just forgot to reflect that in the docs.
2 Views