取消从另一个函数返回的先前可观察对象

Cancel previous observable returned from another function

我有一种情况,如果返回新的可观察对象,我需要取消之前的可观察对象。 见下文

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

您可以将可观察订阅保存到一个变量,然后调用 unsubscribe 如果它被调用过一次,如下所示:

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);

工作 stackblitz:

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