Restart the timer on an rxjs interval

后端 未结 5 1098
傲寒
傲寒 2020-12-19 04:31

I created a class which sets up a pausable rxjs observable on an interval:

export class RepeatingServiceCall {
  private paused = false;
  private o         


        
5条回答
  •  渐次进展
    2020-12-19 04:49

    You can achieve the behavior you are describing with the following snippet:

    const delay = 1000;
    
    const playing = new BehaviorSubject(false);
    
    const observable = playing.pipe(
      switchMap(e => !!e ? interval(delay).pipe(startWith('start')) : never())
    );
    
    observable.subscribe(e => console.log(e));
    
    // play:
    playing.next(true);
    
    // pause:
    playing.next(false);
    
    • When the playing Observable emits true, the switchMap operator will return a new interval Observable.
    • Use the startWith operator to emit an event immediately when unpausing.
    • If you wish to have the interval start automatically when subscribing to the observable, then simply initialize the BehaviorSubject with true.

    StackBlitz Example

提交回复
热议问题