Efficiently Combining and Caching of two flows

33 Views Asked by At

I have two functions which look something like this (exposed by a library, so I can't change it):

fun list() : Flow<List<ID>> and fun propertiesById(id: ID): Flow<List<Prop>>

Essentially, I want to combine them, so that I have the full information about ID + All properties that ID can have (props can be updated)

I can do that by doing something like this:

val result = list().flatMapLatest { ids ->
    val propFlow = ids.map { id ->
        propertiesById(id).map { props ->
            MyClass(id, props)
        }
    }
    combine(propFlow) { it.toList() }
}

This works, and gives me the Flow<List> which has all the information,
the problem is: anytime there is a new ID added/removed - Flow propertiesById is cancelled and started again. which is quite inefficient since propertiesById is doing network calls over and over again.

Is there a way to somehow cache the my propertiesById flow, so when we get a new list of IDs, we can just re-use the flow which has all the information? (i.e avoid cancel and create flow over and over?)

0

There are 0 best solutions below