2017-02-15 45 views
0

我查看过无处不在,但我无法找到如何使用Observable或SimpleTimer创建计时器的解决方案,该计时器可以从特定值重新启动。我尝试退订,然后订阅,但它不会从头开始,也不能使用this.timer = new Observable.timer(...); 任何人都可以帮我解决这个问题吗?Angular 2可重新启动的计时器

谢谢!

回答

0

您可以通过使用switchMap()实现例如重新启动的计时器:

const timerControl$ = new Subject<any>(); 
const timer$ = timerControl$.switchMap(() => Observable.timer(0, 1000)); 

timer$.subscribe(i => console.log(i)); 

// start timer 
timerControl$.next(); 

// re-start timer 
timerControl$.next(); 

编辑:这里是版本,也可以停止计时器:

const timerControl$ = new Subject<number>(); 
const timer$ = timerControl$.switchMap(
    period => period ? Observable.timer(0, period) : Observable.empty() 
); 

timer$.subscribe(i => console.log(i)); 

// start timer 
timerControl$.next(1000); 

// re-start timer with different period 
timerControl$.next(500); 

// stop timer 
timerControl$.next(0); 
+0

谢谢!你能帮我阻止它吗?我试过'timerControl.unsubscribe()'和'timer.unsubscribe()',但他们什么都不做。 – Cataclyst

+0

你应该花一些时间学习RxJS,以便至少了解上面的代码是如何工作的。如果您要在“timer $ .subscribe()”方法返回的订阅上调用它,则“unsubscribe()”将起作用。 –