With Flow what is the "nicest" way to chain two ne...
# flow
j
With Flow what is the "nicest" way to chain two network requests where the second depend on data from the first?
w
a
flatMap
? Although network requests would usually return just a single value so maybe you can just use
suspend fun
?
j
need to mull it over some more. I have a working solution which collects the first flow, requests the second data and then emits a combined result. but it doesn't feel that neat.
w
Well, again if it’s just one value then simple
Copy code
val firstResponse = api.firstRequest()
return api.secondRequest(firstResponse.id)
would work fine. If you need flows for some reason, then I think
Copy code
api.firstRequest()
  .flatMap { api.secondRequest(it.id) }
is the most idiomatic way
j
So I have two repositories, each fetching some data. I have a useCase which integrates with each repository to get this data. So essentially the usecase is handline two flows and needs to merge that data into one flow in a VM. If that makes sense?
I currently, in the usecase, just .collect the data from the first api and then collect the data from the second api and then emit a new flow to the viewmodel
Copy code
suspend fun execute(input) : Flow<Output> {
    return flow {
        repo1.getdata1.collect {
            repo2.getData2.collect {
                emit(CombinedData())
            }
        }
    }
}
pseudocode
which doesn't feel like the most idiomatic way of dealing with it to be honest 😄
w
ah, if you can make both requests in parallel then you might want
combine(flow1, flow2) { result1, result2 -> }
t
your question is the same with me above. flow B will depend on flow A at some point in future. You could view my issue at here, it solved. https://github.com/Kotlin/kotlinx.coroutines/issues/2548
179 Views