gpt4 book ai didi

javascript - 如何在 RXJS retryWhen 内发出/合并另一个可观察值

转载 作者:行者123 更新时间:2023-12-02 21:37:50 25 4
gpt4 key购买 nike

我有一个 api 请求的可观察对象,基本上我在连接失败/错误事件中添加了 retryWhen 。这样做时,我想在请求抛出错误时调度另一个操作(不通知用户系统正在重试......)。

//....
export const saveArticle1 = (action$, state$) =>
action$.pipe(
ofType(AUTO_SAVE_ARTICLE_READY),
withLatestFrom(state$, (a, b) => b),
switchMap(({
article,
}) => {
const payload = getArticlePayload(article);
return ajax.patch(`/api/article/${article.id}`, payload, { 'Content-Type': 'application/json' }).pipe(
flatMap(({ response }) => of({
type: ARTICLE_AUTO_SAVED,
value: response,
})),
retryWhen(errors =>
errors.pipe(
// TODO: I try to concat or merge observable here but no luck
delay(1000),
take(60),
),
),
catchError((ex) => {
articleSaveFailureAlert();
return showErrorNotification('Api Error. Unable to save this article.')(ex);
}),
);
}),
);

retryWhen 内分派(dispatch)另一个操作的最佳方式是什么?或者还有其他方法可以实现这一目标吗?

最佳答案

您可以使用递归循环,其停止条件是尝试次数大于允许的最大尝试次数。然后,您可以将“重试”操作的单个可观察值与补丁可观察值连接起来。如果您编辑代码段以将 maxAttempts 更改为小于 5 的数字,您将看到发出“失败”操作。

顺便说一句 - 在触发进行持久更改的 API 调用时,您可能需要仔细检查 switchMap 的使用情况。 Here's an article这详细解释了这个问题。

const {of, operators, throwError, timer, concat} = rxjs;
const {switchMap, catchError, flatMap} = operators;
const maxAttempts = 60;
const patch = (article, attempt) => {
if (attempt < 5)
return throwError(new Error('server unavailable'));
return of(article);
};
const action$ = of('patch.id');
const saveArticle1 =
action$.pipe(
switchMap((article) => {
const loop = (attempt) => {
return patch(article, attempt).pipe(
flatMap((response) => of({
type: 'saved',
value: response,
})),
catchError(error => {
if (attempt > maxAttempts) return of({ type: 'failed' });

return timer(1000).pipe(
switchMap(() =>
concat(
of({ type: 'retrying' }),
loop(attempt + 1)
)
)
);
})
);
};
return loop(0);
}),
);

saveArticle1.subscribe({
next: x => console.log('next', x),
error: e => console.error(e),
complete: () => console.log('complete')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.4/rxjs.umd.js"></script>

关于javascript - 如何在 RXJS retryWhen 内发出/合并另一个可观察值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60447622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com