接口定義
export interface AttemptRetryWhen {
maxRetryAttempts?: number;//重試次數(shù)
duration?: number;//重試時間間隔
exclude?: boolean;//重試機制擴展
}
實現(xiàn)邏輯
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 星期三 晴 深圳