I want to dynamically change the period/delay of an interval, but unfortunately I am not too familiar with Angular, so I am stuck at this part.
Here is my current code:
timeDiffs : number[] = [] <== this is a preprocessed array with the timemeasurements in milliseconds
this.interval$ = interval(this.timeDiffs[this.intervalCounter ]).subscribe(() => {
//some function calling here
this.intervalCounter ; // next index for next iteration with a different time
})
CodePudding user response:
Use BehaviorSubject
const variable$ = new BehaviorSubject(1); //you can set initial value as per your need
this.variable$.pipe(
switchMap(val => interval(125 * val),
//now apply your various operators chain as per your need
takeWhile(),...
tap(),...
map()...
).subscribe();
this.variable$.next(newValue); //you can use this line to change variable with a new value
CodePudding user response:
You should be able to do this with just concatMap() and timer(). concatMap() guarantee the delays are invoked in correct order only when the previous one completes. timer() will emit once and complete after set delay.
import { from, concatMap, timer } from 'rxjs';
const timeDiffs = [1000, 1000, 3000, 1000];
from(timeDiffs)
.pipe(
concatMap(delay => timer(delay)),
)
.subscribe(console.log)
Demo: https://stackblitz.com/edit/rxjs-nqyxqk?devtoolsheight=60&file=index.ts
