我的用例是将Observable映射到redux成功和失败的操作.我进行网络调用(带有承诺的函数),如果成功,我必须转发成功操作,如果失败而不是错误操作. Observable本身将继续前进.对于我可以搜索的所有内容,RxJS没有用于捕获错误并重试原始文件的机制.我在我的代码中有以下解决方案,我不满意:
error$= new Rx.Subject(); searchResultAction$= search$ .flatMap(getSearchResultsPromise) .map((resuls) => { return { type: 'SUCCESS_ACTION',payload: { results } } }) .retryWhen((err$) => { return err$ .pluck('query') .do(error$.onNext.bind(error$)); }); searchErrorAction$ .map((query) => { return { type: 'ERROR_ACTION',payload: { query,message: 'Error while retrieving data' } } }); action$= Observable .merge( searchResultAction$,searchErrorAction$ ) .doOnError(err => console.error('Ignored error: ',err)) .retry(); action$.subscribe(dispatch);
解决方法
这将重试失败的查询:
var action$= search$ .flatMap(value => { // create an observable that will execute // the query each time it is subscribed const query = Rx.Observable.defer(() => getSearchResultsPromise(value)); // add a retry operation to this query return query.retryWhen(errors$=> errors$.do(err => { console.log("ignoring error: ",err); })); }) .map(payload => ({ type: "SUCCESS_ACTION",payload })); action$.subscribe(dispatcher);
var action$= search$ .flatMap(value => { // create an observable that will execute // the query each time it is subscribed const query = Rx.Observable.defer(() => getSearchResultsPromise(value)); // add a catch clause to "ignore" the error return query.catch(err => { console.log("ignoring error: ",err); return Observable.empty(); // no result for this query })); }) .map(payload => ({ type: "SUCCESS_ACTION",payload })); action$.subscribe(dispatcher);