Devin Stewart
Devin Stewart

Reputation: 3036

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.

Upvotes: 1

Views: 475

Answers (1)

Antoine Xevlabs
Antoine Xevlabs

Reputation: 1031

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(...)

Upvotes: 2

Related Questions