How do I stop Observable.Timer() or Observable.Int

2019-03-03 22:50发布

问题:

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