RxJs/NgRx-是否有一种方法可以“取消"邮件.延迟运算符之后的流 [英] RxJs/NgRx - is there a way to "Cancel" a stream after the delay operator
问题描述
我正在使用NgRx在Angular应用程序中使用轮询方案.
I am using a polling scheme in my Angular application using NgRx.
为简化起见,我有类似以下内容的内容...
To simplify things, I have something like the following...
public stopPolling$ = createEffect(() => this.actions$.pipe(
ofType(actions.stopPolling),
tap(_ => this.isPollingActive = false),
map(_ => actions.stopPolling())
), { dispatch: false });
public continuePolling$ = createEffect(() => this.actions$.pipe(
ofType(actions.getData),
tap(_ => this.logger.debug('continue polling')),
delay(8000),
switchMap(_ => this.pollData())
), { dispatch: false });
private pollData() {
if (!this.isPollingActive)
return;
}
在我的"StopPolling"中,我设置了一个标志,但是如果我在delay(8000)
中时将其重新启动(即isPollingActive等回到true),则延迟将消失并且最终将调用getData多次.
In my "StopPolling" I set a flag, but if it is restarted (ie isPollingActive is et back to true) while I am in the delay(8000)
, the delay will exit and I will end up with the getData being called multiple times.
所以,我的问题是,是否有办法在延迟后逐步调用switchMap(_ => this.pollData())
,即是否有办法在超时时间之前强制延迟退出"?
So, my question is, is there a way to step the switchMap(_ => this.pollData())
being called after the delay - ie is there someway to "force the delay to exit" before the timeout period?
几乎(如果您知道C#/.net).就像manualResetEvent.WaitOne(8000)
一样,可以通过在manualResetEvent对象上调用Set()
来取消.
Almost (if you know C#/.net). like a manualResetEvent.WaitOne(8000)
which can be cancelled by calling Set()
on the manualResetEvent object.
我希望我已经清楚地描述了吗?
I hope I have described this clearly?
预先感谢
推荐答案
您可以使用timer
创建一个延迟后发出的可观察对象,并使用takeUntil
取消订阅以提早退出:
You can create an observable that emits after a delay using timer
and unsubscribe with takeUntil
to exit early:
this.actions$.pipe(
ofType(actions.getData),
tap(_ => this.logger.debug('continue polling')),
switchMap(_ =>
timer(8000).pipe(
takeUntil(this.actions$.pipe(ofType(actions.stopPolling))),
concatMap(() => this.pollData())
)
)
这还可以使您消除副作用this.isPollingActive = false
并确保控制流保持在可观察范围之内.
This might also allow you to remove the side-effect this.isPollingActive = false
and ensure that the control flow remains within the observable.
这篇关于RxJs/NgRx-是否有一种方法可以“取消"邮件.延迟运算符之后的流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!