I have done a small timer, with 3 buttons:
start stop pause/resume (which I haven't done yet)
here is my code so far:
class StopwatchWidgetComponent {
private readonly _start$: Subject<void> = new Subject();
private readonly _stop$: Subject<void> = new Subject();
private readonly _paused$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
readonly counter$: Observable<number>;
constructor() {
this.counter$ = this._start$.pipe(
startWith(0), // trigger emission at launch
switchMap(() => timer(0, 1000).pipe(
takeUntil(this._stop$)
))
);
// Subscribe done later
}
start(): void {
this._start$.next();
}
stop(): void {
this._stop$.next();
}
togglePause(): void {
this._paused$.next(!this._paused$.getValue());
}
}
However, I didn't manage to use the _paused$ subject properly so far.
By looking at github, I found a few topics about this subject:
https://github.com/ReactiveX/rxjs/issues/1542
but I feel that in my case, I would need to get rid of the current timer observable, and trigger a new one starting from the value we stopped at when pausing (and thus having to store that value). Any other operator could help me out here to not have to do that?