Mikhail Mikhail -4 years ago 158
Java Question

RxJava: chaining observables

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

.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)

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

}).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 Source

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


Basically, it'd be:

   .switchMap( someData -> fetchUserDataObservable(someData) )
   .map( userData -> cacheUserData(userData) )
   .subscribe(new Subscriber<YourResult>() {
        public void onCompleted() {
           // observable stream has ended - no more logins possible
        public void onError(Throwable e) {
            // do something
        public void onNext(YourType yourType) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download