I have a question related to Kotlin flow.
Let's say there are two network APIs:
- one is to get a list of IDs; and
- the other one is given an ID, get an user
I what to
- Use the 1st API to get the IDs
- Use the 2nd API to get all the users
- Return the list of the users to UI for display
To me, this looks like a perfect use case for Kotlin flows. I would probably do it like this:
// NetworkApi.kt
interface NetworkApi {
@GET("ids")
suspend fun getIds(): List<Int>
@GET("users/{id}")
suspend fun getUser(id: Int): User
}
And in my ViewModel:
class MyViewModel(private val networkApi: NetworkApi): ViewModel() {
val usersLiveData = flow {
emit(networkApi.getIds())
}.flatMapConcat { // it: List<Int>
val flowList = mutableListOf<Flow<User>>()
val userList = mutableListOf<User>()
for (id in it) {
flowList.add(flow{ emit(networkApi.getUser(id)) })
}
flowList.merge().toList(userList)
userList
}.asLiveData()
}
Note that I used merge
to send out the user requests in parallel (rather than one after another), to shorten the latency.
However, according to the documentation of merge
, it will NOT be "preserving an order of elements".
I would like to have the benefits of parallelization, as well as preserving the order of elements. Is there a way to do that, please?