[Fixed] Dynamically Change RxJS Interval


I have an observable obs with an interval 125*variable, completing an action ever 0.125 seconds. The value of variable will change dynamically throughout my program.

 obs = interval(125*variable).pipe(
    takeWhile(() => this.t < moment('2019-04-16T18:00:00')),
    tap(() => {
      if (!this.isPaused) {
        this.t.add(1, 'minutes'); this.time = this.t.format('LLL');
    map(() => moment(this.time))

How can I change my observable’s interval to use the correct/updated variable value?


Another solution could be like this –

Because "variable" is changing throughout the program. So we first have a BehaviorSubject which will wrap "variable" as an observable and BehaviorSubject will be used to emit the next value for variable

const variable$ = new BehaviorSubject(1); //you can set initial value as per your need

updateVariable(newValue) {

  switchMap(val => interval(125 * val),
  //now apply your various operators chain as per your need

Having this will ensure to start your interval (with 125 * variable) on the emission of each new 'variable' value, canceling the previous interval (switchMap will take care of it). Only subscribe once [there is no need to resubscribe].

Leave a Reply

(*) Required, Your email will not be published