1
votes

I have a subscription to an observable, and I'm trying to run a timer handler five seconds after the last emit value of the observable. The timer is then reset on the next emit

// 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
} 

This works ok, but I'm wondering if there's a way of doing this that is more in line with Rxjs patterns?

2

2 Answers

2
votes

This looks like an easy task for switchMap():

service.on('update')
  .pipe(
    tap(() => this.updateCounter(event)),
    switchMap(() => timer(5000)),
  )
  .subscribe(() => this.timerHandler());
0
votes

What not:

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