【问题标题】:How do I stop Observable.Timer() or Observable.Interval() automatically after certain period of time如何在一段时间后自动停止 Observable.Timer() 或 Observable.Interval()
【发布时间】:2017-03-02 14:23:58
【问题描述】:
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 分钟后自动停止计时器。但是,如果条件满足,我可以手动停止它。不确定在这种情况下手动停止是否仍然正确。

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

【问题讨论】:

    标签: angular rxjs angular2-observables


    【解决方案1】:

    我没有对其进行测试,但这里有一个替代方案,可以在 500 万之后停止:

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

    【讨论】:

    • 如果函数 find() 返回 observable 怎么办?就像我让它 this.find(id).subscribe() 它只调用一次函数。
    • 如果 find 返回一个 observable,请在其上使用 switchMap,这样您就不必自己订阅它,但 switchMap 会为您服务。
    • 知道了! takeUntil() 是我正在寻找的功能。谢谢!!感谢您提出答案的方式。
    • 很高兴你喜欢它并且它很有帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 2017-10-17
    • 2020-11-16
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    相关资源
    最近更新 更多