RxJS Mastery – #32 map

RxJS map lesson title

The RxJS map operator is one of the simplest and most used operators.

Apply a transformation on each source value

The RxJS map operator simply applied a transformation by executing a function. There is no flattening or merging in place. Hence, this simple example here already explains most of the operator:

const result$: Observable<number> = of(1,2,3,4).pipe(
    map(v => v * 2),
);

result$.subscribe((v) => console.info(v));
// 2
// 4
// 6
// 8

The anonymous function v => v * 2 is applied on each number coming from the source Observable.

Map click events to their coordinates with RxJS map

Map can help if there is a source Observable that delivers data, but not all of that data is needed. This is for example the case for http requests in Angular where we usually want to have the json representation of the response and not the whole response. Another case are click events where we usually don’t need the whole event object but just the x and y coordinates of the click:

const clicks$ = fromEvent<PointerEvent>(document, 'click');
const positions = clicks$.pipe(map(event => ({
    x: event.clientX,
    y: event.clientY
})));

Above the PointerEvent is mapped to an object having the two fields x and y. Also, please note the additional () around the x, y object.

Use map instead of the deprecated mapTo operator

In version 9 of RxJS the mapTo operator is removed. This operator was used to directly map to a specific value and not taking into account the value received:

source$.pipe(mapTo('result'));

This should in the future be replaced by an implementation using the map operator:

source$.pipe(() => 'result');

Exercise for the RxJS map operator 💪

What if you pass the following mapper object’s map function (mapper.map) into the RxJS map function? Explore the second argument of RxJS map to get it working.

const mapper = {
  mulitplicator: 3,
  map(v) {
      return v * this.mulitplicator;
  }
};

As always the code examples and exercise solution can be found on GitHub.