接口定义
export interface AttemptRetryWhen {
maxRetryAttempts?: number;//重试次数
duration?: number;//重试时间间隔
exclude?: boolean;//重试机制扩展
}
实现逻辑
export const throwObservableError = (error: any) =>
ErrorObservable.create(error.json ? error.json() : error);// 同时也可以自定义错误,`new ErrorObservable(error.json() ? error.json():error);`;
export const getData = ({ data }) => data;
export const AttemptRetryWhen = (
{ maxRetryAttempts, duration, exclude }: AttemptRetryWhen = {
maxRetryAttempts: 10,
duration: 5000,
exclude: false,
},
) =>
retryWhen(attempts =>
attempts.pipe(
mergeMap((error, i) => {
const retryAttempts = i + 1;
if (exclude || retryAttempts > maxRetryAttempts) {
return throwError(error);
}
console.log(`Attempt ${retryAttempts}: retrying in ${retryAttempts * duration}ms`);
return timer(retryAttempts * duration);
}),
finalize(() => console.log('finished')),
),
);
使用方法
...
this.svc.getUserInfo().pipe(map(getData),AttemptRetryWhen(),catchError(throwObservableError)).subscribe()
...
2019.11.20 星期三 晴 深圳