RxJS retryWhen Example

import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { catchError, map, retryWhen, delay } from 'rxjs/operators';

  subUpdate(apiKey, adminKey) {
    return this.http.post(`${env.api}/sub/update`, {
      api_key: apiKey,
      admin_key: adminKey
    }).pipe(
      map((data: any) => {
        // Queued responces should be retried
        if (data.message === 'Queued') {
          // Error will be picked up by retryWhen
          throw data;
        }
        return data;
      }),
      retryWhen(errors => {
        // Retries
        let retries = 5;

        return errors.pipe(
          map(data => {
            retries--;

            // If HTTP error - send it to catch
            if (data instanceof HttpErrorResponse) {
              throw data;
            }

            // If the max number of retries reached
            if (!retries) {
              throw {
                status: 400,
                error: {message: 'Max Retries Reached'}
              };
            }
          }),
          delay(3000)
        );
      }),
      catchError(this.handleError)
    );
  }

Leave a Comment