Hi Everyone, I work with Android and I have a usec...
# coroutines
i
Hi Everyone, I work with Android and I have a usecase that I need to react when some entities changes on DB. Let's say I have 3 entities and I need to react everytime one of those entities change. I was thinking to use the Room features that allow me to return a Flow from the DAO. My doubt is how I can combine that on a single stream? Thanks in advance
t
Do you mean that you have multiple Dao functions that returns a Flow for different entities, and you just want to be notified when any of those entity tables change ?
i
Yes. I want some way to combine those flows (similar to what mediatorLiveData does)
v
You can use
channelFlow
to combine multiple flows. Something like this:
Copy code
fun <T> mergeFlows(vararg flows: Flow<T>): Flow<T> {
    return channelFlow {
        for (flow in flows) {
            launch { flow.collect { offer(it) } }
        }
    }
}
g
There is already flattenMerge operator for this
i
I don't think the @Vlad solution will work, because the Flows I'll use are of different types. I was looking the operator that @gildor mention and I have one doubt. I'll be able to merge N flows? Looking at the method signature, seems to me that it works for two flows only. I need something very similiar to what mediator live data does: I want someway to react everytime one of my entities change on db (that will be a few)
v
flattenMerge
is a more thought out version of what I had - you will end up in a channel flow where the flow of flows is unpacked:
flowOf(flow1,flow2, flow3, flow4).flattenMerge()
They have to conform to a shared type thought.
i
I did a PoC and what I needed was the
combine
operation, something like that:
Copy code
val combinedFlow = shareFlow
            .combine(latestTransactionFlow) {
                share, transaction -> share to transaction
            }
            .combine(biggestTransactionFlow) { pair, biggestTransaction ->
                Triple(pair.first, pair.second, biggestTransaction)
            }