Angular map vs mergeMap




Asked on May 12, 2019
Hi, What is difference between RxJS map and mergeMap in Angular application?
Provide some examples.



Replied on May 12, 2019

1. map


map is a RxJS pipeable operator. map applies a given function to each element emitted by the source Observable and emits the resulting values as an Observable. map is used with pipe which is an instance method of Observable
Suppose we have an Observable of a string that contains comma separated names.

getStdNames(): Observable<string> {
   return of("Mahesh, Krishna, Ram");
}


Now we will map this string into array and return result into Observable of array of names.

stdNames$: Observable<string[]>;
getStdNames() {
 this.stdNames$ = this.bookService.getStdNames().pipe(
    map(res => res.split(","))
 );
}


We can iterate stdNames$ as following.

<ul>
  <li *ngFor="let name of stdNames$ | async" >
    {{name}}
  </li>
</ul>



2. mergeMap 

RxJS mergeMap operator projects each source value to an Observable and finally they are merged into output Observable using RxJS mergeAll operator.

of('x', 'y', 'z').pipe(
   mergeMap(el => of(1, 2).pipe(
       delay(2000),
       map(num => el+num)        
     )
   )
).subscribe(res => console.log(res)); 


The 'x', 'y', 'z' elements from the source Observable will be emitted to mergeMap. The inner Observable will emit 1, 2 number for every elements of source Observable. We are delaying inner Observable process by 2 seconds and hence before completing request for 'x' element, the 'y' and 'z' element will also enter into mergeMap. So mergeMap will wait for completion of inner Observable for all the three elements and finally will merge them into one Observable as output of mergeMap. 
We can understand merging of inner Observable into one as following. 

of(x1) + of(x2) + of(y1) + of(y2) + of(z1) + of(z2) = of(x1, x2, y1, y2, z1, z2) 

When we subscribe, we will get output x1, x2, y1, y2, z1, z2. 
If inner Observable of mergeMap, is responding for any emitted element from source Observable before getting request for new element, then there is nothing to merge.

Reference:




Write Answer











©2024 concretepage.com | Privacy Policy | Contact Us