Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 783
Mikhail Avatar asked Nov 14 '14 17:11

Mikhail


People also ask

How does RxJava chain work?

subscribeOn is executed during the subscription process and affects both upper, and lower streams. It also can change the thread as many times as you write it. The one closest to the top of the chain is applied. observeOn affects only the lower streams, and is executed during emission.

Is RxJava dead?

RxJava, once the hottest framework in Android development, is dying. It's dying quietly, without drawing much attention to itself. RxJava's former fans and advocates moved on to new shiny things, so there is no one left to say a proper eulogy over this, once very popular, framework.

What's the difference between MAP and FlatMap () in RxJava?

Map transforms the items emitted by an Observable by applying a function to each item. FlatMap transforms the items emitted by an Observable into Observables. So, the main difference between Map and FlatMap that FlatMap mapper returns an observable itself, so it is used to map over asynchronous operations.

What is flatMapCompletable?

This is what flatMapCompletable does: Maps each element of the upstream Observable into CompletableSources, subscribes to them and waits until the upstream and all CompletableSources complete.


1 Answers

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();         }     }); 
like image 200
Benjamin Gruenbaum Avatar answered Sep 22 '22 14:09

Benjamin Gruenbaum