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 simpleflatMap()
with two Observable?
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.
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.
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.
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()?)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With