Using SwitchMap in Angular

The Angular SwitchMap maps each value from the source observable into an inner observable, subscribes to it, and then starts emitting the values from it. It creates a new inner observable for every value it receives from the Source. Whenever it creates a new inner observable it unsubscribes from all the previously created inner observables. Basically it switches to the newest observable discarding all other.

Syntax

The syntax of the SwitchMap operator is as shown below.

project: is a function that we use to manipulate the values emitted by the source observable. The project can accept two arguments. one is value i.e. the value emitted by the source observable. The second argument is index number. The index number starts from 0 for the first value emitted and incremented by one for every subsequent value emitted. It is similar to the index of an array. The project function must return an observable.

SwitchMap Example

To use SwitchMap in Angular first we need to import it our Component or Service.

The following code shows how to use SwitchMap in Angular. We have two observables srcObservable which emits 1,2,3,4 & innerObservable which emits 'A','B','C','D'.


Best Angular Books
The Top 8 Best Angular Books, which helps you to get started with Angular  

The project function is the first argument to the switchMap. It takes the values from the srcObservable. For each value, it receives from the srcObservable (i. e. 1,2,3 &4) it creates a new observable i.e. innerObservable.

SwitchMap automatically subscribes to the innerObservable returned by the project function. The innerObservable emits the values (A,B,C,D), and pushes it to the stream

Hence the subscribers will receive the values A, B, C, D four times. Once for each value of the srcObservable.

SwitchMap Vs Map

The map operators emits value as observable. The SwitchMap creates a inner observable, subscribes to it and emits its value as observable.

The Following example shows the difference between them.

The map operator below maps the value coming from the source observable to a new value by multiplying it by 2. It then emits it into the observable stream. The subscribers will receive the values 2,4,6 & 8.

We can write the above code using SwitchMap as follows. The only thing that changes is how we return the new value in the project function. The map example returns the value as val*2, while the SwitchMap returns new observable (of(val*2)) using the of function. It also subscribes to the newly created observable and emits its value to the stream.

SwitchMap switches to the most recent observable

Whenever SwitchMap subscribes to a new inner observable, it unsubscribes from the previous one.

In the following example, we create an observable from the click event of a button using the fromEvent method. The SwitchMap operator returns an observable using the interval method. The interval method creates an infinite observable, which emits a sequence of integers spaced by a given time interval.

When you click on the button, the clicks observable emits its first value. The switchMap replaces it with the interval observable, which starts emitting value starting from 0 every 500ms.

When you click again, the switchMap unsubscribes from the previous interval observable and starts new one, which again starts to emit value from 0.

Using SwitchMap in Angular

The following are some of the real use cases for the SwitchMap in Angular

With Route Parameters

When we use the Angular Router to Pass parameter to route, we need to read it in our component class. We do that by subscribing to the paramMap to get the id. We then use the id to retrieve the product data.

The code is as shown below.

Consider the example where the user navigates to the /product/1 route. The service will send the query to the database to get the Product with id 1. Now, the user decides to navigate to the route /product/2. This will also result in another query for the Product being sent to the database. It is possible that the result of the second query arrives before the first query. In such a scenario, we will be in the route /product/2 , while our component displays the data of the product 1.

We can easily solve the above issue using the switchMap. When SwitchMap creates the second observable it unsubscribes from all the previous observable. Hence even if the Product 1 data arrives late, it would be discarded as there are no subscribers

Angular Forms ValueChanges event

The similar situations described above can also happen when we subscribe to the ValueChanges event and use that to get data from the back end.

The switchMap ensures that only the result from the last observable populates the Product

The example also uses the debounceTime operator, which emits a value from the source Observable only after a particular time span has passed without another source emission.

References

  1. SwitchMap API

Read More

  1. Pass Parameter to Route
  2. ValueChanges in Angular

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top