I have a list of ids and for each single id i wann...
# coroutines
a
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
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
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
you should add it do your unit tests in case if something changes in the future 🙂
👍 1
e
There is a guarantee on a preserved order. We’ve just forgot to reflect that in the docs.