'Rxjs, retry 3 times, wait 30 seconds, then repeat

I'm using rxjs to connect to a WebSocket service, and in case of failure, I want to retry 3 times, wait 30 seconds, then repeat infinitely, how can I do this?



Solution 1:[1]

I found a solution, first, create the following operator:

function retryWithDelay<T>(
  repetitions: number,
  delay: number
): (a: Observable<T>) => Observable<T> {
  let count = repetitions;
  return (source$: Observable<T>) =>
    source$.pipe(
      retryWhen((errors) =>
        errors.pipe(
          delayWhen(() => {
            count--;
            if (count === 0) {
              count = repetitions;
              return timer(delay);
            }
            return timer(0);
          })
        )
      )
    );
}

Then, use use it like this:

function connect(url: string) {
   return webSocket({ url })
      .pipe(retryWithDelay(3, 30000));
}

Solution 2:[2]

You can do this by doing the following:

    //emit value every 200ms
    const source = Rx.Observable.interval(200);

    //output the observable
    const example = source
        .map(val => {
            if (val > 5) {
                throw new Error('The request failed somehow.');
            }
            return val;
        })
        .retryWhen(errors => errors
            //log error message
            .do(val => console.log(`Some error that occur ${val}, pauze for 30 seconds.`))

            //restart in 30 seconds
            .delayWhen(val => Rx.Observable.timer(30 * 1000))
        );

    const subscribe = example
        .subscribe({
            next: val => console.log(val),
            error: val => console.log(`This will never happen`)
        });


See the working example: https://jsbin.com/goxowiburi/edit?js,console

Be aware that this is an infinite loop and you are not introducing unintended consequences into your code.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rafael de Oliveira
Solution 2 Koktail