我如何订阅和取消订阅可观察对象?

How can I subscribe and unsubscribe from an observable?

我有两个函数,我需要在第一个函数中订阅一个可观察对象,在第二个函数中取消订阅它。但是在我的代码中,我无法从第二个函数访问可观察对象,因为它不在其范围内。

这是我的功能:

 start() {
    this.max = this.duration;
    const interval = Observable.interval(this.selectedSprint.duration);
    interval
      .takeWhile(_ => !this.isFinished)
      .do(i => this.current += 1)
      .subscribe();
    }

    stop() {
    // here I need to unsybscribe to the observable
    this.dialogService.openConfirmDialog('do you want to stop ?')
      .afterClosed().subscribe((result: boolean) => {
        if (result) {
    // if true logic
        }
      });
      }

使用 this.sub = interval.[...].subscribe() 在 class 中保存对您的订阅的引用。

这样,您就可以在第二个函数中调用 this.sub.unsubscribe()

一种解决方案是将订阅存储在您的组件中。

export class Component {
  interval$: Subscription;

  start() {
    this.max = this.duration;
    this.interval$ = Observable.interval(this.selectedSprint.duration)
      .takeWhile(_ => !this.isFinished)
      .do(i => this.current += 1)
      .subscribe();
  }

  stop() {
    // here I need to unsybscribe to the observable
    this.dialogService.openConfirmDialog('do you want to stop ?')
      .afterClosed().subscribe((result: boolean) => {
        if (result) {
          this.interval$.unsubscribe();
        }
    });
  }
}

编辑以回答 OP 的评论

export class Component {
  intervalSub$: Subscription;
  intervalObs: Observable<number>;

  start() {
    this.max = this.duration;
    this.intervalObs$ = Observable.interval(this.selectedSprint.duration)
      .takeWhile(_ => !this.isFinished)
      .do(i => this.current += 1);
   this.intervalSub$ = intervalObs.subscribe();
  }

  stop() {
    // here I need to unsybscribe to the observable
    this.dialogService.openConfirmDialog('do you want to stop ?')
      .afterClosed().subscribe((result: boolean) => {
        if (result) {
          this.intervalSub$.unsubscribe();
        }
    });
  }
  /**
   * If you unsubscribed from the interval and you want to resume
   * (If this.isFinished is true, it won't do a thing)
   */
  resume() {
    this.intervalObs.subscribe();
  }
}

如果您在 class 中,您可以将调用 .subscribe() 返回的 subscription 对象保留为 属性.

start() {
   this.max = this.duration;
   const interval = Observable.interval(this.selectedSprint.duration);
   interval
     .takeWhile(_ => !this.isFinished)
     .do(i => this.current += 1);
   this.intervalSubscription = interval.subscribe();
}

这将允许您在 stop 方法中取消订阅

stop() {
    this.intervalSubscription.unsubscribe(...);
}