Restart the timer on an rxjs interval

后端 未结 5 1091
傲寒
傲寒 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:58

    You can abandon the old timer on start and start a new one on start.

    const { interval, Subject, fromEvent } = rxjs;
    const { takeUntil } = rxjs.operators;
    
    let timer$;
    
    const pause = new Subject();
    
    const obs$ = new Subject();
    
    obs$.subscribe(_ => { console.log('Timer fired') });
    
    function start() {
      timer$ = interval(1000);
      timer$.pipe(takeUntil(pause)).subscribe(_ => { obs$.next(); });
    }
    
    function stop() {
      pause.next();
      timer$ = undefined;
    }
    
    fromEvent(document.getElementById('toggle'), 'click').subscribe(() => {
      if (timer$) {
        stop();
      } else {
        start();
      }
    });
    
    

提交回复
热议问题