问题描述
我创建了一个类,它使用 interval
运算符设置了一个可暂停的 RxJS Observable
:
I created a class which sets up a pausable RxJS Observable
using the interval
operator:
export class RepeatingServiceCall<T> {
private paused = false;
private observable: Observable<T>;
constructor(serviceCall: () => Observable<T>, delay: number) {
this.observable = interval(delay).pipe(flatMap(() => (!this.paused ? serviceCall() : NEVER)));
}
setPaused(paused: boolean) {
this.paused = paused;
}
getObservable() {
return observable;
}
}
这似乎工作正常,但我试图解决的问题是我希望计时器在取消暂停时重置.因此,假设 interval
时间是 interval
上次发出后的 10 秒和 5 秒,setPaused(false)
被调用.在那种情况下,我希望它立即发出,然后重新启动计时器.
This seems to work fine, but the problem I am trying to solve is that I want the timer to reset when unpaused. So, let's say that the interval
time is 10 seconds and 5 seconds after the last time the interval
emitted, setPaused(false)
is called. In that scenario, I want it to emit immediately and then restart the timer.
添加这样的东西会很容易吗?
Would something like that be an easy thing to add?
推荐答案
如果使用timer
代替interval
,并且设置初始延迟为0
,那么您的时间间隔将立即触发.
If you use timer
instead of interval
, and set the initial delay to 0
, then your interval will fire immediately.
您可以使用 takeUntil
操作符来防止间隔始终运行,而 repeatWhen
操作符可以随时重新启动它:
You can use takeUntil
operator to prevent the interval to run always, and repeatWhen
operator to restart it whenever you want:
import { Observable, Subject, timer } from 'rxjs';
import { repeatWhen, switchMap, takeUntil } from 'rxjs/operators';
export class RepeatingServiceCall<T> {
readonly observable$: Observable<T>;
private readonly _stop = new Subject<void>();
private readonly _start = new Subject<void>();
constructor(serviceCall: () => Observable<T>, delay: number) {
this.observable$ = timer(0, delay)
.pipe(
switchMap(() => serviceCall()),
takeUntil(this._stop),
repeatWhen(() => this._start)
);
}
start(): void {
this._start.next();
}
stop(): void {
this._stop.next();
}
}
这是一个有效的 StackBlitz 示例.
P.S.: getter 和 setter 在打字稿中的工作方式不同.所以你不需要经典的 getter 概念,你可以让属性 public
和 readonly
.
P.S.: Getters and setters are working different in typescript. So you do not need classic getter concept, you can just make the attribute public
and readonly
.
这篇关于如何重新启动rxjs间隔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!