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

jean

02/24/2023, 9:47 AM
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

Sabbib Chowdhury

02/25/2023, 2:29 PM
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

jean

02/27/2023, 12:33 PM
I need to keep the StateFlow, so I don’t think combine works in this case
3 Views