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

tseisel

11/26/2019, 9:56 AM
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

tseisel

11/26/2019, 12:02 PM
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

gildor

11/26/2019, 12:40 PM
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

tseisel

11/26/2019, 3:55 PM
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

gildor

11/27/2019, 1:02 AM
But DataFlow or ConflatedBroadcastChannel do not have upstream, that is the whole point
Exactly the same as MutableLiveData
They are observable data holders
2 Views