RxJava Mapping functions

RxJava has several mapping functions. These functions transforms the emitted items to another form or value.

The mapping functions are:

  • map
  • flatMap
  • concatMap
  • flatMapIterable
  • switchMap


map function maps the items to another value of the same or different type

 public void testobservableMap() {
 List<Integer> list = new ArrayList<>();
 IntStream.range(0, 1000).forEach(list::add);

Observable<Integer> observableFromCollection = Observable.from(list).map(e -> e*e);

observableFromCollection.subscribe(new Observer<Integer>() {
 public void onCompleted() {
 System.out.println("observableFromCollection completed");

 public void onError(Throwable e) {
 System.out.println("Error: " + e);

 public void onNext(Integer i) {
 System.out.println("Mapped item: " + i);



flatMap maps items of the type ‘observable’ to plain types

flatMap subscribes to as many emitted Observable’s as possible so does not preserves the emitting order and in case of an error when flattening an observable item in the flatMap operation, flatMap will throw an error.


concatMap subscribes to the observable’s one by one and in sequence

concatMap subscribes to the first Observable and when the current one is completed (on complete has been called), then subscribes to the next observable. As a result, it has the ability to preserve the emit order of the stream. If the order is important, this operation should be used. By example, check first cache, second the local database, as last the service call.


flatMapIterable is a flatMap operation which flattens the iterable items

switcheMap is a flatMap which switches the flattening observable’s when a new one has been received. Thus switchMap will subscribe to the last Observable it encounters and unsubscribe from all previous observable’s. This operation can be used if the old streams are not important anymore once a new type of stream has been encountered.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s