0

I am trying to cancel any pending request using Rxjs. I have gone through some of docs/blogs which suggested to make use of SwitchMap() and debounceTime() operator. I am trying the same but unable to cancel the previous pending request.

In my case I am getting the response of all previous and latest request. Below is the code and problem description.

I am having n number of buttons, on click of each button I am emitting an event (id) using subject and then using that id I am making a http request . What I am trying to achieve is that when a new button is clicked and if there is any previous pending request of some other button click whose response is not yet received, I want to cancel the request, i.e. each time I hit/switch to new button I should get the response of that request only not the older one

this.cancelPreviousReq = this.buttonSwitch$
    .pipe(debounceTime(1000), switchMap(data => this.service.getData(data)))
    .subscribe(data1 => {
      console.log("data ===", data1);
      this.service1.subject.next(data1);
    });

on every button click, emitting an Id

 this.sub1= this.someService.subject1.subscribe((data: any) => {
    this.buttonSwitch$.next(id); // emit the event here
});

service call

getData(id: number): Observable<any>{
    let subject = new Subject<any>();
    let observable = subject.asObservable();
    this.http.get<any>('some url' + id).subscribe((data: any) => {
      if (!data){
        data= this.service.getData1();
      }
      subject.next(data);
    });
    return observable;
  }
shreyansh
  • 1,637
  • 4
  • 26
  • 46
  • 1
    Possible duplicate of [RxJS 6 - Angular 6 - Properly canceling current http request if a new one is triggered](https://stackoverflow.com/questions/51161227/rxjs-6-angular-6-properly-canceling-current-http-request-if-a-new-one-is-tri) – Harun Yilmaz Jul 22 '19 at 09:27
  • `switchMap` does unsubscribe automatically so the problem will be somewhere else. – martin Jul 22 '19 at 09:30
  • remove debounceTime(1000) and everything should works! – Dmitriy Ivanko Jul 22 '19 at 09:38
  • 2
    I see what's wrong there. You subscribe inside `getData` and then return a different Observable therefore the inner subscription is unsubscribable. – martin Jul 22 '19 at 09:48
  • @martin thanks for the observation, I have changed it to getData(id: number): Observable{return this.http.get('some url' + id)}, but still its not working. – shreyansh Jul 23 '19 at 06:09
  • 1
    Can you update the code above. Just to be fully sure there isn‘t another mistake. Basically it should work, atleast from the changes you described – Jan-Niklas Wortmann Aug 08 '19 at 04:18

0 Answers0