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
tseisel
10/09/2019, 6:45 PM
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
igorvd
10/09/2019, 7:53 PM
Yes. I want some way to combine those flows (similar to what mediatorLiveData does)
v
Vlad
10/09/2019, 10:37 PM
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
gildor
10/09/2019, 11:43 PM
There is already flattenMerge operator for this
i
igorvd
10/10/2019, 11:38 AM
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
Vlad
10/10/2019, 12:05 PM
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: