Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between using a compose() and a simple flatMap()?

I just watched the conference by Jake Wharton The State of Managing State with RxJava.

He proposes to transform the events from view to action in this way:

Observable<Event> events = RxView.clicks(view).map(__ -> new Event());
ObservableTransformer<Event, Action> action = events -> events.flatMap(/* ... */);
events.compose(action).subscribe();

I would like to know the difference with this implementation:

Observable<Event> events = RxView.clicks(view).map(__ -> new Event());    
Observable<Action> action = events.flatMap(/* ... */);
action.subscribe();

What is the difference between using a compose() with an ObservableTransformer and a simple flatMap() with two Observable?

like image 454
lopez.mikhael Avatar asked Apr 15 '17 11:04

lopez.mikhael


People also ask

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 compose in Rxjava?

compose() executes immediately when you create the Observable stream, as if you had written the operators inline. flatMap() executes when its onNext() is called, each time it is called. In other words, flatMap() transforms each item, whereas compose() transforms the whole stream.

What does FlatMap do in Rxjava?

The FlatMap operator transforms an Observable by applying a function that you specify to each item emitted by the source Observable, where that function returns an Observable that itself emits items. FlatMap then merges the emissions of these resulting Observables, emitting these merged results as its own sequence.


1 Answers

There is a good explanation, from Daniel Lew, about the differences. In short:

The difference is that compose() is a higher level abstraction: it operates on the entire stream, not individually emitted items.

For more details look at the complete explanation in this article (in the section named What About flatMap()?)

like image 78
GVillani82 Avatar answered Oct 06 '22 02:10

GVillani82