How to subscribe to a subject from Utils method

173 Views Asked by At

I've implemented the 2nd example from this - it works flawlessly and will re-fire the method if it sees a 503.

My goal is to now display a warning message on the front-end when a retry happens on the first go. However the method sits in the utils class away from the component in which I want to set a flag that displays the warning message.

RxJS utils class

export const genericRetryStrategy = (
  {
    maxRetryAttempts = 4,
    scalingDuration = 1000,
    excludedStatusCodes = [],
    retry = new Subject<any>(),
  }: {
    maxRetryAttempts?: number;
    scalingDuration?: number;
    excludedStatusCodes?: number[];
    retry?: any;
  } = {},
) => (attempts: Observable<any>) => {
  return attempts.pipe(
    switchMap((error, i) => {
      const retryAttempt = i + 1;
      // if maximum number of retries have been met
      // or response is a status code we don't wish to retry, throw error
      if (retryAttempt > maxRetryAttempts || excludedStatusCodes.find(e => e === error.status)) {
        return _throw(error);
      }
      // retry after 1s, 2s, 6s and 8s
      if (retryAttempt === 3 || retryAttempt === 4) {
        scalingDuration = 2000;
      }
      console.log(`Attempt ${retryAttempt}: retrying in ${retryAttempt * scalingDuration}ms`);
      return timer(retryAttempt * scalingDuration);
    }),
    finalize(() => console.log('Abandoning..')),
  );
};

..Component.ts

public submit() {
.
.
.

this.someService // The service contains return methods
   .create(data)
   .pipe(
     retryWhen(genericRetryStrategy({
       retry: true,
       excludedStatusCodes: [200],
     })),
     catchError(error => of(error)),
   )
   .subscribe((response: someResponse) => {
     this.someService.saveData(response.data, response.jwt);

I want the RxJS utils class to control when the below is displayed

Frontend

 <p *ngIf="retry" class="warning">
   Retrying..
 </p>

Any examples / ideas on how to achieve this would be great!

Thanks in advance!

0

There are 0 best solutions below