It should retry x
times with a delay of y
. I came up with these explicit criteria while reviewing other approaches:
x
times if an error is thrown.y
before each retry.x
tries are exceeded. A lot of solutions were struggling especially with this.We’ll put together 4 existing RxJS operators to build our own retryWithDelay
operator:
We’ll pipe the input observable into the retryWhen
operator. In there we reuse the other 3 operators:
scan
. We’ll increase the count each time by one. We also overwrite the error attribute each time and keep track of the last error:export function retryWithDelay<T>(
delay: number,
count = 1
): MonoTypeOperatorFunction<T> {
return (input) =>
input.pipe(
retryWhen((errors) =>
errors.pipe(
scan((acc, error) => ({ count: acc.count + 1, error }), {
count: 0,
error: undefined as any,
}),
)
)
);
}
#javascript #programming #angular #typescript #rxjs