我在使用 NgRx 的 Angular 应用程序中使用轮询方案。
为了简化事情,我有如下内容:
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)
,延迟将退出,我最终将多次调用 getData 。
所以,我的问题是,有没有办法一步步switchMap(_ => this.pollData())
延迟后被调用 - 即是否有某种方式可以在超时之前“强制延迟退出”?
几乎(如果你了解 C#/.net)。像一个manualResetEvent.WaitOne(8000)
可以通过调用取消Set()
在 ManualResetEvent 对象上。
您可以创建一个在延迟后发出的可观察对象timer
并取消订阅takeUntil
提前退出:
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
并确保控制流保持在可观察范围内。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)