10 rxjs
如何构造一个以某个预定间隔发射的观测值,但也可以在第二个观测值发射时发射,此时间隔将"重置"以从原点开始再次开始发射.第二次ping?
例如,假设间隔为10分钟.可观测量将在10,20,30等发射.但是让我们说第二个可观测量在时间15发射.然后整体可观测量应在10,15,25,35等处发射.
Mar*_*mba 10
在角度4中,我设法通过以下方式重置间隔
private ngUnSubscribe: Subject<void> = new Subject<void>();
ngOnDestroy() {
this.ngUnSubscribe.next();
this.ngUnSubscribe.complete();
}
ngOnInit() {
this.pillar_timer_interval = IntervalObservable.create(3500);
this.startInterval();
}
startInterval() {
this.pillar_timer_interval
.takeUntil(this.ngUnSubscribe)
.subscribe( ( value ) => {
//whatever function you calling every 3.5s
});
}
resetInterval() {
this.ngUnSubscribe.next();
this.startInterval(); // start the interval again
}
Run Code Online (Sandbox Code Playgroud)
你可以switchMap在第二个下面的第一个流.
//Outer timer fires once initially and then every 15 minutes
Rx.Observable.timer(0, 15 * 60 * 1000 /*15 minutes*/)
//Each outer event cancels the previous inner one and starts a new one
.switchMap(outer => Rx.Observable.interval(10 * 60 * 1000 /*10 minutes*/))
.subscribe(x => console.log(x));
Run Code Online (Sandbox Code Playgroud)
上面的结果将是Observable每十分钟发射一次但在外部Observable发射时重置.
这是我的尝试。它可以满足您的要求,但并不是特别优雅。
import * as Rx from "rxjs/Rx";
const resetter = new Rx.Subject();
const resettableInterval = Rx.Observable.of(0)
.concat(resetter)
.switchMap((value, index) => {
let interval = Rx.Observable.interval(1000);
if (index > 0) {
interval = Rx.Observable.of(-1).concat(interval).map((value) => value + 1);
}
return interval;
});
const since = Date.now();
resettableInterval.subscribe(
(value) => { console.log(`${((Date.now() - since) / 1000).toFixed(1)}: ${value}`); }
);
setTimeout(() => { resetter.next(0); }, 1500);
Run Code Online (Sandbox Code Playgroud)
初始可观察值包含一个值,该值使用 启动间隔switchMap。重置器可观察量是串联的,因此每次发出时都会重置间隔。index运算符提供的参数用于switchMap确定是否发出间隔的初始值。(如果您不关心发出的增量数字,您可以删除map- 它仅用于确保发出的数字重置为零等)
输出应该是:
1.0: 0
1.5: 0
2.5: 1
3.5: 2
4.5: 3
5.5: 4
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7443 次 |
| 最近记录: |