How can I feed a flow with data from another flow?...
# coroutines
j
How can I feed a flow with data from another flow? Some code example :
Copy code
class PaymentViewModel(...) : ViewModel() { // in an android app
    private val _state = MutableStateFlow<PaymentStatus>()
    val state = _state.asStateFlow()

    fun pay() {
        ...
    }

    private fun payWithCard {
        paymentWithCard() // returns a flow of PaymentStatus
    }

    private fun payWithApp {
        payWithApp() // returns a flow of PaymentStatus
    }
}
How can I update
_state
with the data coming from
paymentWithCard()
and
paymentWithApp()
? Do I have to use
collect { … }
on each of them and manually update the state?
s
you can combine on both your flows.
Copy code
val nums = flowOf(1, 2, 3)
val strs = flowOf("one", "two", "three")
nums.combine(strs) { a, b -> "$a -> $b" } // composed value of both flows
    .collect { println(it) }
https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/combine.html
j
I need to keep the StateFlow, so I don’t think combine works in this case