How to stop Observable.Timer () or Observable.Interval () automatically after a certain period of time

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 minutes if the condition if (model ['isActivated']) is not fulfilled. However, if the condition is satisfied, I can stop it manually. Not sure if manual stop in this case is still correct.

Any suggestions with other timer functions are also welcome.

0
source share
1 answer

I have not tested this, but here is an alternative to your suggestion with a 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();
}
+3
source

Source: https://habr.com/ru/post/1676273/


All Articles