Angular 2 reSTARTable timer

故事扮演 提交于 2019-12-12 01:29:22

问题


I've looked everywhere, but I just can't find a solution on how to create a timer with Observable, or SimpleTimer, which I can restart from a specific value. I tried unsubscribing, and then subscribing, but it won't start from the beginning, and neither can I use this.timer = new Observable.timer(...); Can anyone help me with this, please?

Thanks!


回答1:


You can achieve re-startable timer for example by using 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();

EDIT: Here is the version which can also stop the timer:

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);


来源:https://stackoverflow.com/questions/42246350/angular-2-restartable-timer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!