Understanding the map Operator

map belongs to the category of transformation operators, as its primary role is to alter every value emitted by the source observable. For each incoming value, the operator applies a projection function, producing a new output value that is then forwarded to the observer. This behavior closely mirrors the map method found on Array.

In addition to the value itself, the projection function receives an index argument. This index represents the ordinal position of the emitted value since subscription, beginning at 0.

The operational flow of map can be broken down as follows:

  1. Initiate subscription to the source observable.
  2. Upon each emission from the source, invoke the projection function with the current value.
  3. Emit the result returned by the projection function to the observer.
  4. When the source completes, deliver the complete notification to the observer.
  5. If an error occurs in the source, transmit the error notification to the observer.

Practical Applications

map stands out as one of the most frequently employed operators within the RxJS framework. For instance, you might use it to strip whitespace from string values:

const strings = [' some', 'another '];
from(strings).pipe(
   map((value) => value.trim())
).subscribe((s) => console.log(s));

Another typical scenario involves selecting specific properties from an object:

const clicks = fromEvent(document, 'click');
const positions = clicks.pipe(
   map((event: MouseEvent) => {
       return {
           x: event.clientX,
           y: event.clientY
       };
   })
);
positions.subscribe(x => console.log(x));

Interactive Demonstration

Further Reading