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.

+3


source to share


2 answers


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
});

      

+1


source


You can simply use concat

Observables to execute a series of sequences.



    final Observable flowObs = Observable.concat(obs1, obs2, obs3);
    flowObs.subscribe(); //will first execute the subscriber function on obs1, then on obs2, then on obs3

      

0


source







All Articles