https://kotlinlang.org logo
#flow
Title
# flow
j

joakim

03/07/2021, 8:55 PM
With Flow what is the "nicest" way to chain two network requests where the second depend on data from the first?
w

wasyl

03/07/2021, 9:27 PM
a
flatMap
? Although network requests would usually return just a single value so maybe you can just use
suspend fun
?
j

joakim

03/07/2021, 9:37 PM
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

wasyl

03/07/2021, 9:39 PM
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

joakim

03/07/2021, 9:41 PM
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

wasyl

03/07/2021, 10:25 PM
ah, if you can make both requests in parallel then you might want
combine(flow1, flow2) { result1, result2 -> }
t

treatmaster

03/08/2021, 2:18 AM
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
84 Views