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([]))
        );
  • 相关阅读:
    字符串匹配——KMP算法(C++)
    数论——Fibonacci数列(C++)
    数据结构——线段树之二(C++)
    数据结构——线段树之一(C++)
    最后的最后
    开始的开始
    10.25模拟 保留道路
    10.25模拟 列车调度
    10.25模拟 三角形
    洛谷 P1093 奖学金
  • 原文地址:https://www.cnblogs.com/Answer1215/p/15133052.html
Copyright © 2011-2022 走看看