I have a situation where i need to cancel an previous observable if new observable is returned. See below
function fooService(timeOut: number): Observable<string> {
return new Observable(subs => {
setTimeout(() => {
subs.next(new Date().toTimeString());
}, timeOut);
});
}
function barComponent(timeOut: number): void {
// here it should cancel previous subscription if this function called again
fooService(timeOut).subscribe(
time => console.log(time)
);
}
barComponent(5000);
barComponent(2000); // i need to cancel last call
You can save the observable subscription to a variable then call unsubscribe
if it's been called once like this:
let observableInstance; function fooService(timeOut: number): Observable<string> { return new Observable(subs => { setTimeout(() => { subs.next(new Date().toTimeString()); }, timeOut); }); } function barComponent(timeOut: number): void { if (observableInstance) { observableInstance.unsubscribe(); } observableInstance = fooService(timeOut).subscribe(time => console.log(time)); } barComponent(5000); barComponent(2000);
Working stackblitz:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.