简体   繁体   中英

Cancel previous observable returned from another function

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:

https://stackblitz.com/edit/rxjs-mb38xc?devtoolsheight=60

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM