I want to cancel my previous request when newer one comes

I have a text box and i m making a http call on each input character. But my problem is that i want to cancel my request when user enter next character in the case when my previous response not come.

2 answers

  • answered 2019-09-15 22:24 j6m8

    You can't cancel a HTTP request the way you expect; once you send an HTTP request to the server, the request has been sent, and even if you ignore the response, the server will still try to satisfy the request.


    • A "streaming" HTTP request (which can be terminated)
    • If you use an HTTP request to trigger a job to start on the server, and use a separate HTTP request to cancel that job (but this still involves two successful http requests, rather than canceling one)

    You might want to look into throttling or "debouncing" in JavaScript, where a function can be called once on every keypress, conditioned on if it hasn't been called in the past N milliseconds, e.g.

    [EDIT] To be clear, some tools will let you "cancel" an HTTP request that is still in-flight (e.g. rxjs, as the commenter notes). But that doesn't necessary stop your server from processing the call if it's already been received by the server, and furthermore, cancellability is dependent upon your HTTP implementation. Read more here.

  • answered 2019-09-16 01:31 Tony Ngo

    You can use rxjs switchMap operator to do that

    On each emission the previous inner observable (the result of the function you supplied) is cancelled and the new observable is subscribed. You can remember this by the phrase switch to a new observable. This works perfectly for scenarios like typeaheads where you are no longer concerned with the response of the previous request when a new input arrives


    // RxJS v6+
    import { interval, fromEvent } from 'rxjs';
    import { switchMap } from 'rxjs/operators';
    fromEvent(document, 'click')
        // restart counter on every click
        switchMap(() => interval(1000))

    Demotraste from angular university blog. You can see that when new request is coming previous request getting cancel

    enter image description here