Amit Chigadani
Amit Chigadani

Reputation: 29705

How do I stop Observable.Timer() or Observable.Interval() automatically after 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 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.

Upvotes: 1

Views: 4884

Answers (1)

maxime1992
maxime1992

Reputation: 23793

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

Upvotes: 5

Related Questions