1.catchError 的第二个参数,直接返回就是代表重试, 使用标志位控制重试次数
import { of } from 'rxjs/observable/of';
import { map, catchError } from 'rxjs/operators';
let flag = 0;
const source$ = of(1,2,3);
source$.pipe(map((v)=> {
if (v%2 === 0 && flag < 3) {
throw new Error('Bad Number')
}
return v;
}), catchError((err, caught$) => {
flag++;
console.log(`第${flag} 次重试: ${err.message}`);
return caught$;
})).subscribe((res) => {
console.log(res);
})
- 自定义retry
function retryWithDelay<T>(
delaySeconds: number,
count = 1
): MonoTypeOperatorFunction<T> {
return (input) => {
return input.pipe(retryWhen((errors) => {
return errors.pipe(
scan((acc, error) => ({ count: acc.count + 1, error }), {
count: 0,
error: undefined as any,
}),
tap((current) => {
if (current.count > count) {
throw current.error;
}
}),
delay(delaySeconds)
)
})
)}
}