The flatMap
operator help you to transform one event to another Observable
(or transform an event to zero, one, or more events).
It's a perfect operator when you want to call another method which return an Observable
public Observable<String> perform(int i) {
// ...
}
Observable.just(1, 2, 3)
.flatMap(i -> perform(i))
.subscribe(result -> System.out.println("result ->" + result);
flatMap
will serialize perform
subscriptions but events emited by perform
may not be ordered. So you may receive events emitted by the last perform call before events from the first perform
call (you should use concatMap
instead).
If your creating another Observable
in your subscriber, you should use flatMap
instead. The main idea is : never leave the Observable
For example :
Observable.just(1, 2, 3)
.subscribe(i -> perform(i));
can easily be replaced by :
Observable.just(1, 2, 3)
.flatMap(i -> perform(i))
.subscribe();
Reactivex.io documentation : http://reactivex.io/documentation/operators/flatmap.html