更新时间:2023-11-17 16:35:10
例如,您可以使用 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();
这是还可以停止计时器的版本:
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);