Angular2: switchMap not canceling previous http calls

前端 未结 4 441
孤街浪徒
孤街浪徒 2021-02-01 07:40

I am trying to use switchMap to cancel any previous http calls in Angular2. The code is basically

var run = ():Observable => {
        var url = \'         


        
4条回答
  •  一整个雨季
    2021-02-01 08:12

    You can use Subject but if you do so, you have to manage subscription and publish. If you just want a method returning Observable which cancel requests within a interval, here is how I would do that :

    observer: Observer;
    debug = 0;
    
    myFunction(someValue) {
        this.observable = new Observable(observer => {
            if (!this.observer) {
                this.observer = observer;
            }
    
           // we simulate http response time
            setTimeout(() => {
                this.observer.next(someValue);
                this.debug++;
            }, 1000);
        })
        .debounceTime(3000) // We cancel request withing 3s interval and take only the last one
        .switchMap(fn)
        .do(() => {
            console.log("debug", this.debug);
        });
    }
    

    Using the same observer all along let us cancel requests according all we want (debounceTime, distinctUntilChanged, ...).

提交回复
热议问题