0

I have a service that gets triggered to make calls on the backend How can I cancel previous ongoing requests to only get the last request result back my code is :

 this.vehiclesService.getVehiclesByPage(currentState).subscribe(success => {
        this.cache[backendPage] = true;
        this.setPageResult({ ...success, page: backendPage, pageSize: pageInfo.pageSize * 10 });
      });

I tried to add a debounceTime like this but it didn't seem to work

 this.vehiclesService.getVehiclesByPage(currentState).pipe(debounceTime(500)).subscribe(success => {
        this.cache[backendPage] = true;
        this.setPageResult({ ...success, page: backendPage, pageSize: pageInfo.pageSize * 10 });
      });

I believe that a switchMap should do the trick yet I don't know how to combine it with my code Can anyone show me how to add it ?

R0b0t0
  • 390
  • 6
  • 20
  • Once a request is sent it cannot be canceled. You can however, just ignore the response... – Get Off My Lawn May 23 '21 at 20:00
  • how can I only get the response of the last request that got sent? – R0b0t0 May 23 '21 at 20:07
  • Use `takeLast(1)` to get a last emission from a response. – Dmitry S. May 23 '21 at 21:01
  • I would ask about the scenario of how you're sending many requests, it depends on sin the currentState value? I would suggest using switchMap operator – Rebai Ahmed May 24 '21 at 09:17
  • @GetOffMyLawn Http requests can be aborted, for example with [fetch](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort) – NickL May 24 '21 at 10:48
  • Does this answer your question? [how to use switchMap to cancel pending http requests and taking the last subscribe only?](https://stackoverflow.com/questions/49152025/how-to-use-switchmap-to-cancel-pending-http-requests-and-taking-the-last-subscri) – NickL May 24 '21 at 11:37

1 Answers1

1

It looks like you're creating a new observable each time you make the http request. The simplest option is to use a shared Subject that you can push values to.

// create single, shared Subject
let webRequestTriggers = new Subject();

// subscribe to the Subject once at the beginning
function initialise() {
  webRequestTriggers.pipe(
    switchMap(currentState => this.vehiclesService.getVehiclesByPage(currentState))
  )
  .subscribe(success => {
    this.cache[backendPage] = true;
    this.setPageResult({ ...success, page: backendPage, pageSize: pageInfo.pageSize * 10 });
  });
}

// probably in some kind of event handler or function that you have defined somewhere, which is called whenever a page of results is requested
function fetchPagedResults(currentState) {
  webRequestTriggers.next(currentState);
}
NickL
  • 1,870
  • 2
  • 15
  • 35
  • 2
    If this is in a method, each time the method is called you'll probably again create a new subject . So it might be better to move the Subject to a field level. The key solution is `switchMap` tho so yeah the rest is clean up I guess :-) – eko May 24 '21 at 11:07