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;
}