我一直在尝试实现我自己的 RxJS 运算符,以便我可以将其“插入”到我的 Angular 的 HttpClient。我想让请求每 X 毫秒持续一次(轮询),但如果出现错误,我想使用某种增量策略重试请求。这是一个细分:
这是我到目前为止所拥有的:
function repeatWithBackoff<T>(delay: number, maxDelay = 60000) {
return (source: Observable<T>) =>
timer(0, delay).pipe(
concatMap(() => {
return source.pipe(
retryWhen((attempts) => {
return attempts.pipe(
concatMap((attempt, i) => {
const backoffDelay = Math.min(delay * Math.pow(2, i), maxDelay);
return timer(backoffDelay);
})
);
})
);
})
);
}
Run Code Online (Sandbox Code Playgroud)
我的使用方法如下:
httpClient.post(...)
.pipe(repeatWithBackoff(1000, 60000))
.subscribe((x) => console.log('Result', x)); …Run Code Online (Sandbox Code Playgroud)