Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Reset Observable Timer

I have a service where I have a method getting called every 30 seconds automatically. I also have a button which will allow a user to reset the timer, preventing this method from getting called for another 30 seconds. How can I reset my timer so this method won't get called within that 30 seconds if the button is clicked?

COMPONENT

constructor(private service: Service) {
  this.service.initialize();
}

refreshTimer(): void {
  this.service.refreshTimer();
}

SERVICE

initialize(): void {
    timer(0, 30000).subscribe(() => this.refresh());
}

refreshTimer(): void {
  // Need help here
}

As you can see, my component calls initialize() from its constructor, which initializes the timer to run this.refresh() every 30 seconds. The idea is that my html will call refreshTimer() in the component, which will ultimately call refreshTimer() in the service to start the timer over. How can I do this?

Thanks in advance!

like image 912
Josh Avatar asked Aug 12 '26 01:08

Josh


1 Answers

I'd use switchMap that unsubscribes the previous timer and subscribes to the new one that start all over again.

private reset$ = new Subject();

initialize(): void {
  this.reset$
    .pipe(
      startWith(void 0),
      switchMap(() => timer(0, 30000)),
    )
    .subscribe(() => this.refresh());
}

refreshTimer(): void {
  this.reset$.next(void 0);
}

The startWith operator is required to trigger creating the first timer on subscription.

like image 89
martin Avatar answered Aug 14 '26 16:08

martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!