RxJs switchMap Operator

akashvarma9

Akash Varma

Posted on April 30, 2020

RxJs switchMap Operator

Hello everyone πŸ‘‹, I hope you're doing great.

Every RxJs developer should know about this operator.

switchMap

Consider typeahead functionality. Whenever a user enters something we will make calls for each keypress event. Ofcourse, we can use debounce and throttling methods to reduce unnecessary function calls.

Let's say you want to search for Canada. Without rxjs the functionality would be like calling 6 times XHR request. Ideally, we don't want to bother response for the first 5 calls. We want a response only for the 6th call. That achievement would make a great developer. Let's do that.

Add an event listener to the input element and pipe it with switchMap operator.

Alt Text

Note: getCountry method should return Observable

Basically observables should be subscribed. Only then it invokes. SwitchMap will subscribe inner function and here it is subscribing getCountry method.

Tada!!!

Alt Text
If you observe the above image, all the requests got cancelled except last one.

According to official docs, switchMap defines
Projects each source value to an Observable which is merged in the output Observable, emitting values only from the most recently projected Observable.

Thanks for your time✌️

πŸ’– πŸ’ͺ πŸ™… 🚩
akashvarma9
Akash Varma

Posted on April 30, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

RxJs switchMap Operator
javascript RxJs switchMap Operator

April 30, 2020