RxJava: chaining observables

Mikhail picture Mikhail · Nov 14, 2014 · Viewed 34.3k times · Source

Is it possible to implement something like next chaining using RxJava:

loginObservable()
   .then( (someData) -> {
      // returns another Observable<T> with some long operation
      return fetchUserDataObservable(someData);

   }).then( (userData) -> {
      // it should be called when fetching user data completed (with userData of type T)
      cacheUserData(userData);

   }).then( (userData) -> {
      // it should be called after all previous operations completed
      displayUserData()

   }).doOnError( (error) -> {
      //do something
   })

I found this library very interesting, but can't figure our how to chain requests where each other depends on previous.

Answer

Benjamin Gruenbaum picture Benjamin Gruenbaum · Nov 14, 2014

Sure, RxJava supports .map which does this. From the RxJava Wiki:

map

Basically, it'd be:

loginObservable()
   .switchMap( someData -> fetchUserDataObservable(someData) )
   .map( userData -> cacheUserData(userData) )
   .subscribe(new Subscriber<YourResult>() {
        @Override
        public void onCompleted() {
           // observable stream has ended - no more logins possible
        }
        @Override
        public void onError(Throwable e) {
            // do something
        }
        @Override
        public void onNext(YourType yourType) {
            displayUserData();
        }
    });