Search code examples
angularapirxjsobservableswitchmap

How to cancel in flight pending http api calls?


I have a button on my web page on pressing which an http api call is made. It takes some time to get the response and reflect in the page. So is there a way to cancel in flight pending http requests to avoid multiple api calls in case the user presses it multiple time which may result in inconsistent data?


Solution

  • Have you ever considered a scenario where you are not allowed to disable the button.

    Q. So what happens next ?
    A. User is still allowed to press the button.

    But in such scenario, you don't want to make the second call (considering first API call is yet not complete). exhaustMap automatically cancels the second call if first call is in progress. That's the beauty of exhaustMap.

    For such scenarion exhaustMap from RXJS is useful.

    Read this nice article to understand it further

    Dummy Code

    fromEvent(this.saveButton.nativeElement, 'click')
        .pipe(
            exhaustMap(() => this.saveCourse(this.form.value))
        )
        .subscribe();
    

    OR switchMap could be handy where you have one request to go and suddenly second request comes, so it will cancel out the first request and start the process for second one.

    fromEvent(this.saveButton.nativeElement, 'click')
            .pipe(
                swtichMap(() => this.saveCourse(this.form.value))
            )
            .subscribe();
    

    It depends on the scenario that is applicable for your application.