zoukankan      html  css  js  c++  java
  • [RxJS] Retry with increasing time

    import { Observable, throwError, timer } from 'rxjs';
    import { mergeMap, finalize } from 'rxjs/operators';
    
    export const genericRetryStrategy = ({
      maxRetryAttempts = 3,
      scalingDuration = 1000,
      excludedStatusCodes = [],
    }: {
      maxRetryAttempts?: number;
      scalingDuration?: number;
      excludedStatusCodes?: number[];
    } = {}) => (attempts: Observable<any>) => {
      return attempts.pipe(
        mergeMap((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 throwError(error);
          }
          console.log(`Attempt ${retryAttempt}: retrying in ${retryAttempt * scalingDuration}ms`);
          // retry after 1s, 2s, etc...
          return timer(retryAttempt * scalingDuration);
        }),
        finalize(() => console.log('We are done!'))
      );
    };

    USAGE:

        const careTeams$: Observable<any[]> = getMockData([]).pipe(
          map((results) => {
            if (result.length == 0) {
              throw results;
            }
            return results;
          }),
          retryWhen(
            genericRetryStrategy({
              maxRetryAttempts: 10,
              scalingDuration: 100,
              excludedStatusCodes: [500],
            })
          ),
          catchError((err) => of([]))
        );
  • 相关阅读:
    星空Password
    股票交易
    【1】博客目录
    事务
    C#基础索引
    C# String
    MSIL
    Evaluation Stack
    Spring源码编译以及导入Intellij IDEA的操作步骤
    WebFlux响应式编程简单示例
  • 原文地址:https://www.cnblogs.com/Answer1215/p/15133052.html
Copyright © 2011-2022 走看看