rxjs map

RxJS Map Function

RxJS is a library for reactive programming using Observables. The map operator is one of the most commonly used operators in RxJS. It is used to transform the data emitted by an Observable. The map operator applies a function to each value emitted by the Observable and returns a new Observable that emits the transformed values.

Syntax

// Using pipeable operator syntax
observable$.pipe(
  map(value => transformFunction(value))
);

// Using the method chain syntax
observable$.map(value => transformFunction(value));

The map function takes a function as an argument which will be applied to each value emitted by the Observable. The function should return the transformed value to be emitted by the new Observable.

Example

Let's say we have an Observable that emits a stream of numbers:

// Create an Observable that emits numbers
const numbers$ = of(1, 2, 3, 4, 5);

// Print out the original numbers
numbers$.subscribe(value => console.log(value));

The output of the above code will be:

1
2
3
4
5

We can use the map operator to transform the numbers into their square:

// Transform the numbers using the map operator
const squaredNumbers$ = numbers$.pipe(
  map(value => value * value)
);

// Print out the squared numbers
squaredNumbers$.subscribe(value => console.log(value));

The output of the above code will be:

1
4
9
16
25

As you can see, the map operator transformed each number into its square and the new Observable emitted the transformed values.

Multiple Ways to Use Map Operator

There are multiple ways to use the map operator in RxJS. You can use it with the pipeable operator syntax or with the method chain syntax. Here's an example of using map with the method chain syntax:

// Using map with the method chain syntax
const doubledNumbers$ = numbers$.map(value => value * 2);

// Print out the doubled numbers
doubledNumbers$.subscribe(value => console.log(value));

The output of the above code will be:

2
4
6
8
10

As you can see, we used the map operator with the method chain syntax to double each number emitted by the Observable.

Conclusion

The RxJS map operator is a powerful tool for transforming data emitted by Observables. It can be used in a variety of ways to transform data into any format you need. With its easy-to-use syntax and flexibility, it's no wonder why the map operator is one of the most commonly used operators in RxJS.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe