可观察计时器:return 计时器完成后的操作
Observable timer: return action after timer finished
我正在尝试在 React 应用程序中使用来自 rxjs 的计时器创建一个简单的投票工作器。
为此,我创作了一部史诗。非常简单 - 我在 1 分钟内每 5 秒从服务器获取一些信息。
const processPollEpic = action$ => action$.pipe(
ofType(POLL_START),
mergeMap(() => timer(0, 5000).pipe(
exhaustMap(() => from(service.getSmth()).pipe(map(resp => {
if (resp.isSuccess) {
return processPollStop();
}
return processPollContinue();
}))),
takeUntil(action$.ofType(POLL_STOP)),
take(12),
)),
);
它运行良好,但我无法解决一个极端情况。
现在我returnPOLL_STOP只有在服务器响应成功时才会动作。
但是时间到了,我什么都不做。
我可以return在计时器结束时执行一些操作吗?
你可以拆分里面的内链mergeMap
:
concat(
timer(0, 5000).pipe(
exhaustMap(() => from(service.getSmth()).pipe(map(resp => {
if (resp.isSuccess) {
return processPollStop();
}
return processPollContinue();
}))),
take(12),
),
of(CREATE_OTHER_ACTION_HERE),
).pipe(
takeUntil(action$.ofType(POLL_STOP)),
)
concat
仅在前一个链完成后才会订阅 of()
。然后 takeUntil
仍然可以完成整个链,因此 concat
将取消订阅其内部 Observable。
顺便说一句,请确保您从 'rxjs'
而不是 'rxjs/operators'
.
导入正确的 concat
我正在尝试在 React 应用程序中使用来自 rxjs 的计时器创建一个简单的投票工作器。
为此,我创作了一部史诗。非常简单 - 我在 1 分钟内每 5 秒从服务器获取一些信息。
const processPollEpic = action$ => action$.pipe(
ofType(POLL_START),
mergeMap(() => timer(0, 5000).pipe(
exhaustMap(() => from(service.getSmth()).pipe(map(resp => {
if (resp.isSuccess) {
return processPollStop();
}
return processPollContinue();
}))),
takeUntil(action$.ofType(POLL_STOP)),
take(12),
)),
);
它运行良好,但我无法解决一个极端情况。 现在我returnPOLL_STOP只有在服务器响应成功时才会动作。 但是时间到了,我什么都不做。
我可以return在计时器结束时执行一些操作吗?
你可以拆分里面的内链mergeMap
:
concat(
timer(0, 5000).pipe(
exhaustMap(() => from(service.getSmth()).pipe(map(resp => {
if (resp.isSuccess) {
return processPollStop();
}
return processPollContinue();
}))),
take(12),
),
of(CREATE_OTHER_ACTION_HERE),
).pipe(
takeUntil(action$.ofType(POLL_STOP)),
)
concat
仅在前一个链完成后才会订阅 of()
。然后 takeUntil
仍然可以完成整个链,因此 concat
将取消订阅其内部 Observable。
顺便说一句,请确保您从 'rxjs'
而不是 'rxjs/operators'
.
concat