Hello, I am trying to concat two flows in a way th...
# coroutines
a
Hello, I am trying to concat two flows in a way that I get results sequentially when I collect on it
Copy code
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")
}
my expectation here was that I will get first result first and then second after sometime as response comes from server. But the problem here is collect only gets called after server returns result.
l
Hello @Abhishek Bansal That is expected behavior, because
flowOf
cannot be called before its parameters are evaluated, which here, suspends. You probably want to use
flow { emit(data) }
instead.
a
Hello @louiscad, Thanks for your reply! I understand, since I do not have data directly here whats the best way to concatenate two flows directly? Something that behaves like
Observable.concat()
?
l
@Abhishek Bansal I'm not familiar with RxJava, but if you just describe in plain English what you want your code to do exactly, I can show you how to do it with coroutines and flows.
a
ah okay, I wanted to implement cache then network strategy. What I want is a final flow where I get data from cache if and when its available and then data from network if when its available. I do not want to wait for any of these events. I was able to solve it with this code
Copy code
flow {
   remoteDataSource.getDataFromCache()
   .catch { error -> Timber.e(error) }
   .onCompletion {
       remoteDataSource.getDataFromServer()
            .collect {
                 emit(it)
            }
    }.collect { emit(it) }
}
I wonder if a clean
concat
like operator available in Flow for this.