androidrx-javaobservablesubscriberretrolambda

How to run 2 queries sequentially in a Android RxJava Observable?


I want to run 2 asynchronous tasks, one followed by the other (sequentially). I have read something about ZIP or Flat, but I didn't understand it very well...

My purpose is to load the data from a Local SQLite, and when it finishes, it calls the query to the server (remote).

Can someone suggests me, a way to achieve that?

This is the RxJava Observable skeleton that I am using (single task):

    // RxJava Observable
    Observable.OnSubscribe<Object> onSubscribe = subscriber -> {
        try {

            // Do the query or long task...

            subscriber.onNext(object);
            subscriber.onCompleted();
        } catch (Exception e) {
            subscriber.onError(e);
        }
    };

    // RxJava Observer
    Subscriber<Object> subscriber = new Subscriber<Object>() {
        @Override
        public void onCompleted() {
            // Handle the completion
        }

        @Override
        public void onError(Throwable e) {
            // Handle the error
        }

        @Override
        public void onNext(Object result) {

          // Handle the result

        }
    };

    Observable.create(onSubscribe)
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(subscriber);

Solution

  • The operator to do that would be merge, see http://reactivex.io/documentation/operators/merge.html.

    My approach would be to create two observables, let's say observableLocal and observableRemote, and merge the output:

    Observable<Object> observableLocal = Observable.create(...)
    Observable<Object> observableRemote = Observable.create(...)
    Observable.merge(observableLocal, observableRemote)
              .subscribe(subscriber)
    

    If you want to make sure that remote is run after local, you can use concat.