Hi ! I have a design problem with `Flow`. I have a...
# coroutines
t
Hi ! I have a design problem with
Flow
. I have a source flow the emits the current result of a request in database whenever it changes (like a
Flow
returned by Android Room). I decided to expose the result of those request with a repository.
Copy code
interface DataSource {
    val flow: Flow<List<Foo>>
}

class Repository(
    private val source: DataSource
)
    val diff: Flow<Diff<Foo>> get() = TODO()
    suspend fun getLatest(): List<Foo> = TODO()
}
How can I transform the source flow to adapt it to the needs of the
Repository
? (The
Diff
is calculated from the latest and the previous list of `Foo`s.) Is it possible to cache the latest value just like Android
LiveData
, to avoid costly database queries when repeateadly reading the latest values ?
t
The
conflate
operator may be part of the solution, but it does not cache the latest value, each call to
getLatest()
still triggers a database query
g
There is no direct Flwo analogue of BehaviorSubject/LiveData. It in development now (there is a PR, search for DataFlow) But you can use ConflatedBroadcastChannel in coroutines, there is asFlow() extension, so you can expose such channel as Flow
t
Good to know ! I'm very enthousiastic about that DataFlow . @gildor Do you know how it behaves in case of an exception in the upstream ? In my case, the source flow throws a specific exception if some permission is not denied. Will
DataFlow
rethrow that exception or re-collect the upstream ? I'd really like option 2.
g
But DataFlow or ConflatedBroadcastChannel do not have upstream, that is the whole point
Exactly the same as MutableLiveData
They are observable data holders