How to reset Observable.interval
我该如何构造一个以某个预定间隔发射的可观测对象,但又可以使其在第二个可观测对象发射时发射,此时将"重置"该间隔以从初始间隔开始重新发射第二次ping的点?
例如,假设间隔为10分钟。该可观察对象将在10、20、30等处发射。但是,让我们说第二个可观察对象在时间15处发出。那么整个可观察对象应在10、15、25、35等处ping。
在angular4中,我设法通过以下
重置了间隔
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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 } |
您可以
1 2 3 4 5 | //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)); |
上面的结果将是一个
这是我的尝试。它可以满足您的要求,但并不特别优雅。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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); |
初始可观察值包含单个值,该值使用
输出应为:
1 2 3 4 5 6 7 | 1.0: 0 1.5: 0 2.5: 1 3.5: 2 4.5: 3 5.5: 4 ... |