Reputation: 1229
I am happily using Retrofit with RxJava in my app, but I don't know how to properly chain network calls which don't really return anything except telling that the call succeeded.
One example is function which sends all updated items to server. First I want to call loginManager.refreshLogin()
and then synchronizeInventories()
and synchronizeItems()
, wait until they are both done and return something indicating the UI can be updated.
Right now, the function 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 it's the right way to do it.
Upvotes: 3
Views: 995
Reputation: 4799
You can simply use concat
to execute a number of Observables in series.
final Observable flowObs = Observable.concat(obs1, obs2, obs3);
flowObs.subscribe(); //will first execute the subscriber function on obs1, then on obs2, then on obs3
Upvotes: 0
Reputation: 13450
Observable<List<Object>>
is returned because synchronizeInventories()
and synchronizeItems()
return different types of objects thus .merge()
returns an Observable<Object>
.
If both methods returned same objects then it you be a specific class e.g.:
.flatMap(o -> Observable.merge(Observable.just("a"), Observable.just("b")))
.doOnNext(new Action1<String>() {
@Override
public void call(String s) {
}
})
A way to avoid the general Object class is to use .zip()
and use the helping Pair<>
class:
.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
});
Upvotes: 1