在一段时间后如何自动停止Observable.Timer()或Observable.Interval() [英] How do I stop Observable.Timer() or Observable.Interval() automatically after certain period of time

查看:1101
本文介绍了在一段时间后如何自动停止Observable.Timer()或Observable.Interval()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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.

推荐答案

我没有对其进行测试,但这是您的提案的替代方法,该提案在5百万之后停止:

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

这篇关于在一段时间后如何自动停止Observable.Timer()或Observable.Interval()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆