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