What is Map Operator - RXJS

What is Map Operator - RXJS

RxJS Higher-Order Mapping operators are very important for many common operations in reactive programming. The higher-order mapping operators of RxJS: switchMap, mergeMap, concatMap and exhaustMap are among the most widely used RxJS operators we use on a daily basis.

The map operator is a Transformation Operator. It takes values from one Observable, transforms them, and creates a new Observable that emits the transformed values.  

Most important and useful operator

map() operator is used for data stream transformation operator

Used for transform data according requiremnt

For examplae if we receiving data from server but need to modify it our requiqmrnet we can use map

It receives obserble and returns modified observable(Modified data)

We can also modify data after we received but instead of doing this RXJS provides us a better way of doing this using MAP

Map operator applies a given function to each value emitted by source observable and any resulting values as an observable.

import { map,interval } from "rxjs/operators";
..........
sub2: Subscription;
ngOnInit(){

const broadCastdata = interval(1000);

 this.sub2 = broadCastdata
      .pipe(map((data) => data * 10))
      .subscribe((res) => {
        console.log(res);
      });

 setTimeout(() => {
      this.sub2.unsubscribe();
    }, 10000);
}
//output:
10,20,30,40,50,60,70,80,90

In the above example, the value is passed from the map one by one and multiply the value by 10.

Example2

  import { from } from 'rxjs';
  import { map } from 'rxjs/operators';
    
  const source = from([
        { name: 'James', age: 26 },
        { name: 'John', age: 21 },
        { name: 'Smith', age: 20 }
    ]);
    //To get only person names using map
    const result= source
                  .pipe(map(({ name }) => name))
                  .subscribe(val => console.log(val));;
   //output: 
"James"
"John"
"Smith"

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

You might also like

Leave a Comment