I am trying to implement cache then network strategy for my API call using Kotlin
Flows
.
Here is what I am trying right now
flowOf(
remoteDataSource.getDataFromCache() // suspending function returning Flow<Data>
.catch { error -> Timber.e(error) },
remoteDataSource.getDataFromServer() // suspending function returning Flow<Data>
).flattenConcat().collect {
Timber.i("Response Received")
}
Problem here is collect
is only called when getDataFromServer
returns. My expectation is that I should get first event from cache and then second event from server after a few milliseconds. In this case "Response Received"
gets printed twice but immediately one after other.
In this other variant "Response Received"
only gets printed once that is after getDataFromServer()
returns.
remoteDataSource.getDataFromCache() // suspending function returning Flow<Data>
.catch { error -> Timber.e(error) }
.flatMapConcat {
remoteDataSource.getDataFromServer() // suspending function returning Flow<Data>
}
.collect {
Timber.i("Response Received")
}
I was using RxJava's Flowable.concat()
before and it was working perfectly. Is there something in Kotlin Flows which can emulate that behaviour?