When is the latest request?
At what point in time would you define what the latest request is?
You would need to collect
every click the user does and at some other point execute the request. but that seems rather weird
Every http request observable will complete once the request itself has completed.
If you don't have any overlapping requests switchMap
won't do anything because there isn't anything to switch.
You can verify that if you add a delay
see https://stackblitz.com/edit/rxjs-about-switchmap-jhy3v4
If you add a delay to your request to simulate latency you get the result you would expect from switchMap
Without the delay your request is so fast it has completed as soon as you click again and there is nothing to switch because the inner observable has already completed hence you get all the results because it's a new stream of events.
This is also why for example last
or takeLatest
won't help here.
Here's what I would to
https://stackblitz.com/edit/rxjs-about-switchmap-jhy3v4
In the button with id test I would use debounceTime
in combination with switchMap
and enabling/disabling the button
const click3$ = fromEvent(document.querySelector('#test'), 'click');
switchMapExample2$.subscribe((val) => {
console.table(val);
});
const button = document.querySelector('#test');
const switchMapExample3$ = click3$.pipe(
tap(() => button.setAttribute('disabled', 'disabled')),
debounceTime(500),
tap(() => console.log('inside switchMap - click happend')),
switchMap(() => {
console.log('inside switchMap - start http request');
return httpCall$.pipe(
tap((val) => console.log('inside switchMap - http response ', val))
);
}));
switchMapExample3$.subscribe((val) => {
console.table(val);
button.removeAttribute('disabled');
});
Just be aware of RxJS: Avoiding switchMap-Related Bugs posted by Oles Savluk.