问题
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!
回答1:
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.
回答2:
You should unsubscribe then re-subscribe to the timer observable
t = timer(0, 30000);
sub: Subscription;
initialize(): void {
this.sub = this.t.subscribe(() => this.refresh());
}
refreshTimer(): void {
this.sub.unsubscribe();
this.initialize();
}
or you can just have one method
t = timer(0, 30000);
sub: Subscription;
initTimer(): void {
this.sub && this.sub.unsubscribe();
this.sub = this.t.subscribe(() => this.refresh());
}
来源:https://stackoverflow.com/questions/50592260/angular-2-reset-observable-timer