I am trying to use switchMap to cancel any previous http calls in Angular2. The code is basically
var run = ():Observable => {
var url = \'
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, ...).