Angular + switchMap Example

By Arvind Rai, January 25, 2024
This page will walk through Angular and RxJS switchMap operator Example. 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 Observable. switchMap 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.

1. Using switchMap in Search Operation

Here we will discuss using switchMap in search functionality. 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.

Error handling with switchMap:
We can use catchError with switchMap to handle any error as following.
searchBook() {
  this.bookId.valueChanges.pipe(
    debounceTime(500),
    switchMap(id => {
       console.log(id);
       return this.bookService.getBook(id);
    }),
    catchError(err => of(null))
  ).subscribe(res => this.book = res);
} 

2. Using switchMap to Access URL Parameter in Routing

To access URL query parameter, we use switchMap operator in routing. Suppose there are many links and on the click of the link, detail is shown. If the user clicks more than one link in a very short span of time then it is necessary that detail should be shown of only latest clicked link. As we know that switchMap stops emitting values of inner Observable if new inner Observable starts emitting. Find the code snippet to use switchMap to access parameter in angular routing.
ngOnInit() {
  this.route.params.pipe(
	switchMap((params: Params) => this.bookService.getBook(+params['id']))
  )
  .subscribe(book => this.book = book);
} 

3. Output

Download source code and run the application. Find the print-screen of the output.
Angular + switchMap Example

4. Reference

RxJS switchMap

5. Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us