Hi there!
I'm having issues trying to implement caching with Flow.
Requirements: return a cached value and then follow up with network request result. The cached value must be observed regardless of network call success or failure.
Implementation looks like
fun data(): Flow = flowOf(
flowOf(cachedValue),
networkCallFlow
). flattenConcat()
which is then observed in a ViewModel and mapped to UI state
data()
.onEach { .. }
.map { uiState(data) }
.catch { emit(uiState(error)) }
It works fine when the network call succeeds.
The problem is, when
networkCallFlow
throws an exception (no network), the
cachedValue
is never mapped, however it triggers the
onEach
handler. My guess is that the emission of the
cachedValue
does not guarantee that it will be observed, and the exception halts the Flow before the consumption of the
cachedValue
happens or while it is in progress.
Is my understanding correct?
Is there any way to adjust the Flow to fit the requirements?
The code:
https://pl.kotl.in/3U8jVprL-