'How to set a delay on Error in Angular / NgRx Subscription with Interval

I would like my interval to wait 5 seconds on an error before trying to hit my service again. Much like it does on a successful call.

Using Angular 12 and NgRx 6, I have the following code in my ngOnInit()

    this.switchMapSubscription = interval(5000).pipe(
        startWith(0),
        switchMap(() => this.service.getData(dataKey))
    ).subscribe(
        data => {
          this.buildData(data);
        }
    );

When this.service.getData() receives an error, it retries immediately and continuously.

I have tried to put a delay in the interval():

 this.switchMapSubscription = interval(5000).pipe(
        startWith(0),
        switchMap(() => this.service.getData(dataKey)),
        retryWhen(error => error.pipe(delay(5000)))
    ).subscribe(
        data => {
          this.buildData(data);
        }
    );

And in the subscribe():

 this.switchMapSubscription = interval(5000).pipe(
        startWith(0),
        switchMap(() => this.service.getData(dataKey)),
    ).subscribe(
        data => {
          this.buildData(data);
        },
        err => err.pipe(delay(5000))
    );

Both of my attempted solutions gave me the same results as the original code.



Solution 1:[1]

When the error is present, you want to delay, but when it's not present you want to set back the right one.

this.switchMapSubcribtion = this.service.getData(dataKey).pipe(
    retryWhen(err => return err.pipe(delay(5000)))
).subscribe(...)

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