rxjs/operators#retryWhen TypeScript Examples

The following examples show how to use rxjs/operators#retryWhen. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: 1inch.api.service.ts    From gnosis.1inch.exchange with MIT License 6 votes vote down vote up
function delayedRetry(delayMs: number, maxRetry = DEFAULT_MAX_RETRIES) {
  let retries = maxRetry;

  return (src: Observable<any>) =>
    src.pipe(
      retryWhen((errors: Observable<any>) => errors.pipe(
        delay(delayMs),
        mergeMap(error => retries-- > 0 ? of(error) : throwError(error))
      ))
    );
}
Example #2
Source File: artichoke.ts    From closer-sdk.js with MIT License 6 votes vote down vote up
constructor(
    private artichokeApi: ArtichokeApi,
    private callFactory: CallFactory,
    private roomFactory: RoomFactory,
    private loggerService: LoggerService,
    private heartbeatTimeoutMultiplier: number,
    private fallbackReconnectDelayMs: number,
  ) {
    // Do not move this as a property accessor, it must be only one object to make rx `share` operator work.
    this.connection = merge(
      this.artichokeApi.connection$.pipe(
        filter(serverEvents.OutputHeartbeat.is),
        tap((ev: serverEvents.OutputHeartbeat) => this.handleHeartbeatEvent(ev)),
        ignoreElements(),
      ),
      this.artichokeApi.connection$.pipe(
        filter(serverEvents.Hello.is),
        tap(ev => this.handleHelloEvent(ev)),
      ),
    ).pipe(
      finalize(() => this.handleDisconnect()),
      // On WebSocket error
      retryWhen(errors => this.delayReconnect(errors)),
      takeUntil(this.serverUnreachableEvent),
      // On WebSocket gracefull close
      repeatWhen(attempts => this.delayReconnect(attempts)),
      // IMPORTANT
      // Share the observable, so the internal logic would behave like one consistent stream
      // Without this operator, if client subscribes two times, we would have
      // two heartbeats answers and reconnections logic
      share(),
    );
  }
Example #3
Source File: login.component.ts    From budget-angular with GNU General Public License v3.0 6 votes vote down vote up
login() {
    const loginRequest: LoginRequest = {
      email: this.f.email.value,
      password: this.f.password.value,
    };

    this.authService
      .login(loginRequest)
      .pipe(retryWhen(this.invalidOtp(loginRequest)))
      .subscribe((user) =>
        this.router.navigate([
          this.authService.getInitialPathForRole(user.role),
        ])
      );
  }
Example #4
Source File: dia-backend-asset-uploading.service.ts    From capture-lite with GNU General Public License v3.0 6 votes vote down vote up
private uploadProof$(proof: Proof) {
    const scalingDuration = 1000;
    const attempBase = 2;
    return this.diaBackendAssetRepository.addCapture$(proof).pipe(
      first(),
      catchError((err: unknown) => {
        if (
          err instanceof HttpErrorResponse &&
          err.error.error.type === 'duplicate_asset_not_allowed'
        ) {
          return this.diaBackendAssetRepository.fetchByProof$(proof);
        }
        return throwError(err);
      }),
      map(diaBackendAsset => {
        proof.diaBackendAssetId = diaBackendAsset.id;
        return proof;
      }),
      retryWhen(err$ =>
        err$.pipe(
          mergeMap((_, attempt) => {
            return timer(attempBase ** attempt * scalingDuration);
          })
        )
      )
    );
  }
Example #5
Source File: api.service.ts    From storm with MIT License 6 votes vote down vote up
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      // Catch 401 errors and ask for the API key.
      // Redo the request with the provided API key in basic auth headers
      catchError((err: ApiException) => {
        if (err.status != 401) {
          return throwError(err)
        }

        return this.ask$.pipe(
          switchMap(key => {
            const withAuthHeaderReq = req.clone({
              headers: req.headers.set('Authorization', 'Basic ' + btoa(':' + key))
            });

            return next.handle(withAuthHeaderReq)
          })
        )
      }),

      // Keep retrying 401 errors
      retryWhen(errors => errors.pipe(
        takeWhile((err: ApiException) => err.status === 401)
      ))
    )
  }
Example #6
Source File: backend_srv.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
private toFailureStream = (options: BackendSrvRequest): MonoTypeOperatorFunction<FetchResponse> => inputStream =>
    inputStream.pipe(
      filter(response => response.ok === false),
      mergeMap(response => {
        const { status, statusText, data } = response;
        const fetchErrorResponse: ErrorResponse = { status, statusText, data };
        return throwError(fetchErrorResponse);
      }),
      retryWhen((attempts: Observable<any>) =>
        attempts.pipe(
          mergeMap((error, i) => {
            const firstAttempt = i === 0 && options.retry === 0;

            if (error.status === 401 && this.dependencies.contextSrv.user.isSignedIn && firstAttempt) {
              return from(this.loginPing()).pipe(
                catchError(err => {
                  if (err.status === 401) {
                    this.dependencies.logout();
                    return throwError(err);
                  }
                  return throwError(err);
                })
              );
            }

            return throwError(error);
          })
        )
      )
    );
Example #7
Source File: backend_srv.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
private toDataSourceRequestFailureStream = (
    options: BackendSrvRequest
  ): MonoTypeOperatorFunction<FetchResponse> => inputStream =>
    inputStream.pipe(
      filter(response => response.ok === false),
      mergeMap(response => {
        const { status, statusText, data } = response;
        const fetchErrorResponse: ErrorResponse = { status, statusText, data };
        return throwError(fetchErrorResponse);
      }),
      retryWhen((attempts: Observable<any>) =>
        attempts.pipe(
          mergeMap((error, i) => {
            const requestIsLocal = !options.url.match(/^http/);
            const firstAttempt = i === 0 && options.retry === 0;

            // First retry, if loginPing returns 401 this retry sequence will abort with throwError and user is logged out
            if (requestIsLocal && firstAttempt && error.status === 401) {
              return from(this.loginPing()).pipe(
                catchError(err => {
                  if (err.status === 401) {
                    this.dependencies.logout();
                    return throwError(err);
                  }
                  return throwError(err);
                })
              );
            }

            return throwError(error);
          })
        )
      )
    );
Example #8
Source File: load.component.ts    From blockcore-hub with MIT License 5 votes vote down vote up
// Attempts to initialise the wallet by contacting the daemon.  Will try to do this MaxRetryCount times.
    private tryStart() {
        let retry = 0;
        const stream$ = this.apiService.getNodeStatus().pipe(
            retryWhen(errors =>
                errors.pipe(delay(this.TryDelayMilliseconds)).pipe(
                    tap(errorStatus => {
                        if (retry++ === this.MaxRetryCount) {
                            throw errorStatus;
                        }
                        this.log.info(`Retrying ${retry}...`);
                    })
                )
            )
        );

        this.subscription = stream$.subscribe(
            (data: NodeStatus) => {
                this.apiConnected = true;
                this.statusIntervalSubscription = this.apiService.getNodeStatusCustomInterval(350) // Get status quickly during initial load.
                    .subscribe(
                        response => {
                            this.featureStatus = response.featuresData.map(d => {
                                return {
                                    name: d.namespace.split('.').pop(),
                                    state: d.state,
                                    initialized: d.state === 'Initialized'
                                };
                            });

                            let loadingStatus = this.featureStatus.filter(x => x.name == 'WalletFeature');

                            if (loadingStatus.length > 0 && loadingStatus[0].initialized) {
                                this.statusIntervalSubscription.unsubscribe();
                                this.start();
                            }
                        }
                    );
            }, (error: any) => {
                this.log.info('Failed to start wallet');
                this.loading = false;
                this.loadingFailed = true;
            }
        );
    }
Example #9
Source File: load.component.ts    From EXOS-Core with MIT License 5 votes vote down vote up
// Attempts to initialise the wallet by contacting the daemon.  Will try to do this MaxRetryCount times.
    private tryStart() {
        let retry = 0;
        const stream$ = this.apiService.getNodeStatus().pipe(
            retryWhen(errors =>
                errors.pipe(delay(this.TryDelayMilliseconds)).pipe(
                    tap(errorStatus => {
                        if (retry++ === this.MaxRetryCount) {
                            throw errorStatus;
                        }
                        this.log.info(`Retrying ${retry}...`);
                    })
                )
            )
        );

        this.subscription = stream$.subscribe(
            (data: NodeStatus) => {
                this.apiConnected = true;
                this.statusIntervalSubscription = this.apiService.getNodeStatusCustomInterval(350) // Get status quickly during initial load.
                    .subscribe(
                        response => {
                            this.featureStatus = response.featuresData.map(d => {
                                return {
                                    name: d.namespace.split('.').pop(),
                                    state: d.state,
                                    initialized: d.state === 'Initialized'
                                };
                            });

                            const loadingStatus = this.featureStatus.filter(x => x.name === 'WalletFeature');

                            if (loadingStatus.length > 0 && loadingStatus[0].initialized) {
                                this.statusIntervalSubscription.unsubscribe();
                                this.start();
                            }
                        }
                    );
            }, (error: any) => {
                this.log.info('Failed to start wallet');
                this.loading = false;
                this.loadingFailed = true;
            }
        );
    }
Example #10
Source File: app.component.ts    From blog2020 with MIT License 5 votes vote down vote up
constructor() {
    this.options = this.tempOptions;
    this.mergeOptions = {series: {data: [{value: NaN, name: ''}]}};

    const webSocketSubject = webSocket('ws://localhost:8080/sensor');
    webSocketSubject.pipe(retryWhen((errors) => errors.pipe(delay(10_000))))
      .subscribe(value => console.log(value));
  }
Example #11
Source File: app.component.ts    From StraxUI with MIT License 5 votes vote down vote up
private getStatusThroughApi(): void {
    console.log("Getting status from API.");
    let retry = 0;
    const stream$ = this.apiService.getNodeStatus(true).pipe(
      retryWhen(errors =>
        errors.pipe(delay(this.TryDelayMilliseconds)).pipe(
          tap(errorStatus => {
            if (retry++ === this.MaxRetryCount) {
              throw errorStatus;
            }
            console.log(`Retrying ${retry}...`);
          })
        )
      )
    );

    this.subscriptions.push(stream$.subscribe(
      () => {
        this.subscriptions.push(this.statusIntervalSubscription = this.apiService.getNodeStatusInterval(true)
          .subscribe(
            response => {
              if(response) {
                const statusResponse = response.featuresData.filter(x => x.namespace === 'Stratis.Bitcoin.Base.BaseFeature');
                const lastFeatureResponse = response.featuresData.find(x => x.namespace === this.lastFeatureNamespace);
                if (statusResponse.length > 0 && statusResponse[0].state === 'Initialized'
                  && lastFeatureResponse && lastFeatureResponse.state === 'Initialized') {
                  this.loading = false;
                  this.statusIntervalSubscription.unsubscribe();
                  this.router.navigate(['login']);
                }
              }
            }
          )
        );
      }, error => {
        this.errorMessage = error.message;
        console.log('Failed to start wallet');
        this.loading = false;
        this.loadingFailed = true;
      }
    ));
  }