Mikhail Mikhail -4 years ago 158
Java Question

RxJava: chaining observables

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 Source

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();
        }
    });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download