map
map
is part of the so-called transformation operators group because it’s used to transform each item received from the source observable. The operator passes each source value through a projection function to get corresponding output value and emits it to an observer. The idea is very similar to the standard map method on Array
.
The projection function applied to each value emitted by the source also receives the index
parameter, which indicates the number of an element that has happened since the subscription, starting from the number 0.
map
operator works in the following way:
- Subscribe to a source observable
- When a new value arrives from a source observable, execute the projection function for the current value
- Send the returned value to the observer
- Once the source observable completes, send the complete notification to the observer
- If the source observable throws an error, send the error notification to the observer
Usage
map
operator is one of the most used operators in RxJS library. For example, here’s how you can use it to trim spaces from strings:
const strings = [' some', 'another '];
from(strings).pipe(
map((value) => value.trim())
).subscribe((s) => console.log(s));
One common usage includes retrieving a set of 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));