Javascript 如何在RXJS retryWhen内发射/合并另一个可观察对象
我有一个可观察的api请求,基本上我在事件连接失败/错误中添加了Javascript 如何在RXJS retryWhen内发射/合并另一个可观察对象,javascript,reactjs,redux,rxjs,redux-observable,Javascript,Reactjs,Redux,Rxjs,Redux Observable,我有一个可观察的api请求,基本上我在事件连接失败/错误中添加了retryWhen。在执行此操作时,我希望在请求抛出错误时发送另一个操作(不通知用户系统正在重试…) //.... export const saveArticle1 = (action$, state$) => action$.pipe( ofType(AUTO_SAVE_ARTICLE_READY), withLatestFrom(state$, (a, b) => b), switchM
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
内分派另一个操作的最佳方式是什么?或者有其他方法来实现这一点吗?您可以使用递归循环,其停止条件是尝试次数大于允许的最大尝试次数。然后,您可以将“重试”操作的单个可观察项与补丁可观察项连接起来。如果编辑代码段以将maxtures
更改为小于5的数字,您将看到发出“failure”操作
顺便说一下,在触发进行持久更改的API调用时,您可能需要仔细检查switchMap
的使用情况。这就详细地解释了这个问题
const{of,操作符,抛出器,计时器,concat}=rxjs;
const{switchMap,catchError,flatMap}=运算符;
常量最大尝试数=60;
常量补丁=(文章,尝试)=>{
如果(尝试次数<5)
返回抛出器错误(新错误(“服务器不可用”);
归还(物品);
};
const action$=of('patch.id');
常数1=
动作$.pipe(
switchMap((文章)=>{
常量循环=(尝试)=>{
返回补丁(文章,尝试).pipe(
平面图((响应)=>of({
键入:“已保存”,
值:响应,
})),
catchError(错误=>{
if(尝试>最大尝试)返回({type:'failed'});
返回计时器(1000)。管道(
开关映射(()=>
海螺(
的({type:'retrying'}),
循环(尝试+1)
)
)
);
})
);
};
返回回路(0);
}),
);
保存条款1.订阅({
next:x=>console.log('next',x),
错误:e=>console.error(e),
complete:()=>console.log('complete')
});代码>
我想你必须点击点击(()=>this.store.dispatch(…)
,因为我想你不想用这个动作触发重新订阅。谢谢,这很有效。虽然我不得不将您的示例稍作更改,作为switchMap
expected a observatives<代码>返回计时器(1000).pipe(switchMap(()=>of({type:'retrying'}).pipe(concat(loop)(尝试+1 k)))
@TomMarulakpipe
需要一个类似的运算符,而返回一个可观察的。仔细检查它是否在做你认为它在做的事情