DEV Community

Akash Varma
Akash Varma

Posted on

1

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✌️

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

đź‘‹ Kindness is contagious

Dive into this informative piece, backed by our vibrant DEV Community

Whether you’re a novice or a pro, your perspective enriches our collective insight.

A simple “thank you” can lift someone’s spirits—share your gratitude in the comments!

On DEV, the power of shared knowledge paves a smoother path and tightens our community ties. Found value here? A quick thanks to the author makes a big impact.

Okay