Hello everyone 👋, I hope you're doing great.
Every RxJs developer should know about this operator.
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.
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.
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✌️