如何在一段时间后自动停止 Observable.Timer() 或 Observable.Interval()

Ami*_*ani 1 rxjs angular2-observables angular

public function(id: number) {
    this.periodicCheckTimer = Observable.timer(10000, 5000).subscribe(
        () => {
          let model = this.find(id);
          if (model['isActivated']) {
            this.periodicCheckTimer.unsubscribe();
          }
        });
  }
Run Code Online (Sandbox Code Playgroud)

如果条件if(model['isActivated'])不满足,我想在 5 分钟后自动停止计时器。但是,如果条件满足,我可以手动停止它。不确定在这种情况下手动停止是否仍然正确。

对其他计时器功能的任何建议也表示赞赏。

max*_*992 5

我没有测试过,但这里有一个替代方案,在 5mn 后停止:

function (id: number) {
  // emit a value after 5mn
  const stopTimer$ = Observable.timer(5 * 60 * 1000);

  Observable
    // after 10s, tick every 5s
    .timer(10000, 5000)
    // stop this observable chain if stopTimer$ emits a value
    .takeUntil(stopTimer$)
    // select the model
    .map(_ => this.find(id))
    // do not go further unless the model has a property 'isActivated' truthy
    .filter(model => model['isActivated'])
    // only take one value so we don't need to manually unsubscribe
    .first()
    .subscribe();
}
Run Code Online (Sandbox Code Playgroud)