How do I stop Observable.Timer() or Observable.Interval() automatically after certain period of time

人走茶凉 提交于 2019-12-02 15:53:10

问题


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

I want to stop the timer automatically after 5 mins if the condition if(model['isActivated']) is not satisfied. However if the condition satisfies I can stop it manually. Not sure if the manual stop is still correct in this case.

Any suggestions with other timer functions are also appreciated.


回答1:


I didn't test it out, but here's an alternative to your proposal with the stop after 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();
}


来源:https://stackoverflow.com/questions/42557993/how-do-i-stop-observable-timer-or-observable-interval-automatically-after-ce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!