How to reset Observable.interval

How can I build an observable that emits at some predetermined interval, but can also be done to emit when the second observed radiation is emitted, at that moment the interval will be β€œreset” to start emitting again in the original interval, starting from the point of the second ping ?

For example, suppose the interval is 10 minutes. The observable would be radiated at 10, 20, 30, etc. But let's say the second observable when emitted at time 15. Then the total observable should be ping at 10, 15, 25, 35, etc.

+5
source share
3 answers

You can switchMap first thread under the second.

 //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)); 

The result of the above will be an Observable , which is emitted every ten minutes, but gets reset when an external Observable triggered.

+5
source

In angular 4, I managed to reset the interval with the following

 private ngUnSubscribe: Subject<void> = new Subject<void>(); ngOnDestroy() { this.ngUnSubscribe.next(); this.ngUnSubscribe.complete(); } ngOnInit() { this.pillar_timer_interval = IntervalObservable.create(3500); this.startInterval(); } startIntervale() { this.pillar_timer_interval .takeUntil(this.ngUnSubscribe) .subscribe( ( value ) => { //whatever function you calling every 3.5s }); } resetInterval() { this.ngUnSubscribe.next(); this.startInterval(); } 
+3
source

Here is my attempt. He does what you want, but it is not particularly elegant.

 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); 

The original observable contains one value that kick starts the interval using switchMap . The observed reset is combined, so each time it emits an interval, reset. The index parameter provided by the switchMap operator is used to determine if the initial value for the interval is emitted. (If you don't need incremental numbers that are emitted, you can remove map - it is used only to ensure that the emitted reset numbers are zero, etc.)

The output should be:

 1.0: 0 1.5: 0 2.5: 1 3.5: 2 4.5: 3 5.5: 4 ... 
+1
source

All Articles