switchMap is not cancelling previous HTTP call

1.6k Views Asked by At

one of angular service method(http call) created with switchMap operator,so it can reject/cancel the previous rest API calls if new one arrived. it is working fine and make a backend call but it not reject any BE call but it sequentially calling every call and wait for all of BE call to response, it should reject previous calls.

where I am doing wrong ?

stackblitz example

to create first observer event I am using from() method and by each typing it calls HTTP get API.

enter image description here

1

There are 1 best solutions below

2
On

That's because you're calling updateSearch() on every key press which means you're creating many chains that run in parallel instead of making a single chain that can unsubscribe the switchMaped Observable:

You achieve what you need with for example Subject:

s = new Subject();

s.pipe(
  switchMap(y => {
    return this.http.get("https://jsonplaceholder.typicode.com/users").pipe(
      delay(2000),
      map(z => {
        return z;
      })
    );
  ));

updateSearch(value) {
  s.next(value);
}