[英]How to dynamically change the period/delay of an interval for Angular / RxJS
我想动态改变一个间隔的周期/延迟,但不幸的是我对Angular不太熟悉,所以我卡在这部分。
这是我当前的代码:
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
})
使用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
你应该可以只用concatMap()
和timer()
来做到这一点。 concatMap()
保证仅在前一个完成时才以正确的顺序调用延迟。 timer()
将在设置延迟后发出一次并完成。
import { from, concatMap, timer } from 'rxjs';
const timeDiffs = [1000, 1000, 3000, 1000];
from(timeDiffs)
.pipe(
concatMap(delay => timer(delay)),
)
.subscribe(console.log)
现场演示: https://stackblitz.com/edit/rxjs-nqyxqk?devtoolsheight=60&file=index.ts
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.