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

Abhishek Bansal

02/12/2020, 4:49 PM
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

louiscad

02/12/2020, 9:04 PM
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

Abhishek Bansal

02/13/2020, 6:23 AM
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

louiscad

02/13/2020, 7:47 AM
@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

Abhishek Bansal

02/13/2020, 7:49 AM
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.
6 Views