Angular map vs switchMap




Asked on November 19, 2018
What is difference between Angular map and switchMap?



Replied on November 19, 2018
map and switchMap both are RxJS operators. Angular 6 integrates RxJS 6 which has been shipped with pipeable operators that is used independent of Observable.

1. map


map is a RxJS pipeable operator. map applies a given function to each element emitted by the source Observableand emits the resulting values as an Observablemap is imported as following.
import { map } from 'rxjs/operators'; 
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> 
It will print 

Mahesh
Krishna
Ram


2. switchMap


RxJS switchMap emits Observable after applying the given function to each item emitted by source Observable. The Observable emitted by given function that is also called inner Observable, is returned by switchMap operator. switchMap starts emitting items emitted by inner Observable. When a new inner Observable is emitted, the switchMap stops emitting items from previous inner Observable and starts emitting items from latest inner Observable. It continues to do in the same way for all subsequent inner ObservableswitchMap is a RxJS pipeable operator and it is used within pipe function of Observable from RxJS 6. switchMap is imported from rxjs/operators as following.
import { switchMap } from 'rxjs/operators'; 
We can use debounceTime with switchMap to delay the emitting of values from source Observable for the given amount of time. The scenarios to use switchMap are search functionality, accessing URL parameter etc.

For example in search operation, user may frequently change search keyword. So it is important that we should get result only with latest search keyword. For any keyword switchMap will emit items from inner Observable and if before completion a new search keyword is hit, then switchMap will stop emitting previous inner Observable and start emitting the latest inner Observable. Hence user always gets the result for latest search keyword. switchMap is used as following.
searchBook() {
  this.bookId.valueChanges.pipe(
     switchMap(id => {
       console.log(id);
       return this.bookService.getBook(id);
     })
  ).subscribe(res => this.book = res);
} 
Using switchMap with debounceTime:
debounceTime delays the emit of new value from source Observable for the given time after an emit from source Observable has taken place. If within the delay due time, more than one values arrived, then debounceTime keeps track of most recent value and emits the latest one from source Observable once due time is over. Find the code snippet for switchMap with debounceTime.
searchBook() {
  this.bookId.valueChanges.pipe(
     debounceTime(500),
     switchMap(id => {
       console.log(id);
       return this.bookService.getBook(id);
     })
  ).subscribe(res => this.book = res);
} 
The advantage of using debounceTime is that switchMap does not get every search keyword which has been entered and changed within the given delay time by the user because debounceTime emits only the latest value from source Observable only after the given delay time is over. Hence some useless processing by switchMap is avoided. In the above example once the value from source Observable is emitted by debounceTime then only after 500 milliseconds, the latest value from source Observable will be emitted to switchMap operator. 






Replied on July 04, 2019
Hello folk,
Such a perfect tutorial. It help me to clearly understanding the concept of map and switchMap and also the different between them. And also with concrete example: the search functionality.

Thank you very much!


Write Answer











©2024 concretepage.com | Privacy Policy | Contact Us