代码之家  ›  专栏  ›  技术社区  ›  Drenai

rxjs在订阅处理程序中创建计时器?

  •  1
  • Drenai  · 技术社区  · 7 年前

    我订阅了一个Observable,并试图在Observable的最后一个Emit值5秒后运行一个计时器处理程序。然后定时器在下一次发射时重置

    // If the service does not emit for 5 second, the timeout handler is called, 
    // then the timer begins again on the next service emit
    service.on('update')
                .subscribe((event) => {                
                    this.updateCounter(event);
                    // Clear previous timer
                    this.timerSub && this.timerSub.unsubscribe()
                    // Create new timer
                    this.timerSub = timer(5000)
                        .subscribe( () => {
                            this.timerHandler();
                        });
                });
    
    ....
    timerHandler() {
       // do something
    } 
    

    这很好用,但我想知道是否有一种方法更符合rxjs模式?

    2 回复  |  直到 7 年前
        1
  •  1
  •   martin    7 年前

    这看起来是个简单的任务 switchMap() :

    service.on('update')
      .pipe(
        tap(() => this.updateCounter(event)),
        switchMap(() => timer(5000)),
      )
      .subscribe(() => this.timerHandler());
    
        2
  •  0
  •   Meir    7 年前

    什么不:

    const events$ = service.on('update');
    events$.subscribe(this.updateCounter);
    events$.delay(5000).subscribe(timerHandler);