Chained Observations with No Significant Return Values
I happily use Retrofit with RxJava in my application, but I don't know how to properly hook up network calls that don't actually return anything except to say the call succeeded.
One example is a function that sends all updated items to the server. I want to call first loginManager.refreshLogin()
, and then synchronizeInventories()
and synchronizeItems()
, wait for them to complete, and return something indicating that the UI can be updated.
The function now looks like this:
public Observable<List<Object>> synchronize() {
return loginManager.refreshLogin()
.flatMap(o -> Observable.merge(
synchronizeInventories(),
synchronizeItems()
))
.toList();
}
refreshLogin()
returns Observable.just(new Object())
, synchronizeInventories()
and synchronizeItems()
return Observable.empty()
.
Everything works now, but I don't think this is the correct way to do it.
source to share
Observable<List<Object>>
returns because synchronizeInventories()
and synchronizeItems()
return different types of objects, therefore .merge()
returns Observable<Object>
.
If both methods return the same objects, then you are a specific class for example.
.flatMap(o -> Observable.merge(Observable.just("a"), Observable.just("b")))
.doOnNext(new Action1<String>() {
@Override
public void call(String s) {
}
})
The way to avoid the generic Object class is to use .zip()
and use the class Pair<>
:
.flatMap(o -> Observable.zip(just("a"), just(123), (s, s2) -> new Pair<>(s, s2)))
.doOnNext(pair -> {
pair.first // get the first object
pair.second // geth the second
});
source to share