rxjs/operators#finalize TypeScript Examples

The following examples show how to use rxjs/operators#finalize. 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: 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 #2
Source File: deposit-form.component.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
public createDeposit(): void {
    const brbcAmount = this.lpService.parseInputValue(this.brbcAmountCtrl.value);
    const usdcAmount = this.lpService.parseInputValue(this.usdcAmountCtrl.value);

    this.lpModalService
      .showDepositModal(brbcAmount, usdcAmount)
      .pipe(
        switchMap(result => {
          if (result) {
            this._loadingDepositBtn$.next(true);
            return this.lpService
              .createDeposit(usdcAmount)
              .pipe(finalize(() => this._loadingDepositBtn$.next(false)));
          } else {
            return of(false);
          }
        })
      )
      .subscribe(makeDeposit => {
        if (makeDeposit) {
          this.lpNotificationService.showSuccessDepositNotification();
          this.router.navigate(['liquidity-providing']);
        }
      });
  }
Example #3
Source File: scanned-item-manager.service.ts    From pantry_party with Apache License 2.0 6 votes vote down vote up
perfomSave(item: ReadyScannedItem) {
    this.updateScannedItemWithoutVersionBump(
      item.barcode,
      {saveInProgress: true}
    );
    const lastUndoKey = this.pvtUndoKey[item.barcode];
    const undo$ = lastUndoKey ? this.undoCallback(lastUndoKey) : EMPTY;

    concat(
      undo$.pipe(
        map(() => delete this.pvtUndoKey[item.barcode])
      ),
      this.saveCallback(item).pipe(
        map(r => {
          this.pvtUndoKey[item.barcode] = r;

          this.updateScannedItemWithoutVersionBump(
            item.barcode,
            { lastSavedVersion: item.currentVersion }
          );
        })
      )
    ).pipe(
      takeUntil(this.ngUnsubscribe),
      finalize(() => this.updateScannedItemWithoutVersionBump(
        item.barcode,
        {saveInProgress: false}
      )),
      take(1)
    ).subscribe();
  }
Example #4
Source File: lookup-capability.component.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
public onLookup(): void {
    const nilQualifierIfEmpty = this.form.get(NILQUALIFIER_IF_EMPTY).value;
    const qualifier = SciParamsEnterComponent.toParamsDictionary(this.form.get(QUALIFIER) as FormArray, false);
    const nilQualifierOrUndefined = nilQualifierIfEmpty ? {} : undefined;

    const filter: ManifestObjectFilter = {
      id: this.form.get(ID).value || undefined,
      type: this.form.get(TYPE).value || undefined,
      qualifier: Object.keys(qualifier).length ? qualifier : nilQualifierOrUndefined,
      appSymbolicName: this.form.get(APP_SYMBOLIC_NAME).value || undefined,
    };
    this.capabilities$ = Beans.get(ManifestService).lookupCapabilities$(filter)
      .pipe(finalize(() => this.capabilities$ = null));
  }
Example #5
Source File: file-upload.service.ts    From worktez with MIT License 6 votes vote down vote up
pushFileToTaskStorage(fileUpload: FileUpload, basePath: string, folderName: string): Observable<number> {
    this.fileUploadStatus = true;
    const filePath = `${basePath}/${fileUpload.file.name}`;
    const storageRef = this.storage.ref(filePath);
    const uploadTask = this.storage.upload(filePath, fileUpload.file);

    uploadTask.snapshotChanges().pipe(
      finalize(() => {
        storageRef.getDownloadURL().subscribe(downloadURL => {
          fileUpload.url = downloadURL;
          fileUpload.name = fileUpload.file.name;
          this.saveFileData(fileUpload, basePath, folderName).then((data) => {
            if(this.backendService.getOrganizationDomain()) {
              this.readFiles(this.backendService.getOrganizationDomain(), folderName);
            }
          });
        });
      })
    ).subscribe();

    return uploadTask.percentageChanges();
  }
Example #6
Source File: form-changes-until-destroyed.spec.ts    From angular-padroes-e-boas-praticas with MIT License 6 votes vote down vote up
describe('formChangesUntilDestroyed', () => {
  it('should unsubscribe from the component form', () => {
    @UntilDestroy()
    @Component({ template: '' })
    class MockComponent {
      disposed = false;
      form = new FormControl('');

      subscription = formChangesUntilDestroyed(this, this.form)
        .pipe(
          finalize(() => this.disposed = true)
        )
        .subscribe();
    }

    TestBed.configureTestingModule({
      declarations: [MockComponent]
    });

    const fixture = TestBed.createComponent(MockComponent);

    expect(fixture.componentInstance.disposed).toBeFalsy();
    fixture.destroy();
    expect(fixture.componentInstance.disposed).toBeTruthy();
  });
});
Example #7
Source File: logging-interceptor.ts    From blockcore-hub with MIT License 6 votes vote down vote up
intercept(req: HttpRequest<any>, next: HttpHandler) {
        const started = Date.now();
        let ok: string;

        // extend server response observable with logging
        return next.handle(req)
            .pipe(
                tap(
                    // Succeeds when there is a response; ignore other events
                    event => ok = event instanceof HttpResponse ? 'succeeded' : '',
                    // Operation failed; error is an HttpErrorResponse
                    error => ok = 'failed'
                ),
                // Log when response observable either completes or errors
                finalize(() => {
                    const elapsed = Date.now() - started;
                    const msg = `${req.method} "${req.urlWithParams}"
             ${ok} in ${elapsed} ms.`;

                    this.log.info(msg);
                })
            );
    }
Example #8
Source File: forgot-password.component.ts    From angular-10-signup-verification-boilerplate with MIT License 6 votes vote down vote up
onSubmit() {
        this.submitted = true;

        // reset alerts on submit
        this.alertService.clear();

        // stop here if form is invalid
        if (this.form.invalid) {
            return;
        }

        this.loading = true;
        this.alertService.clear();
        this.accountService.forgotPassword(this.f.email.value)
            .pipe(first())
            .pipe(finalize(() => this.loading = false))
            .subscribe({
                next: () => this.alertService.success('Please check your email for password reset instructions'),
                error: error => this.alertService.error(error)
            });
    }
Example #9
Source File: pending-verification.page.ts    From fyle-mobile-app with MIT License 6 votes vote down vote up
resendVerificationLink(email: string) {
    this.isLoading = true;

    this.routerAuthService
      .resendVerificationLink(email)
      .pipe(
        finalize(async () => {
          this.isLoading = false;
        }),
        catchError((err) => {
          if (err.status === 422) {
            this.router.navigate(['/', 'auth', 'disabled']);
          } else {
            this.currentPageState = PageState.failure;
          }
          return throwError(err);
        })
      )
      .subscribe(() => {
        this.currentPageState = PageState.success;
      });
  }
Example #10
Source File: data-view-map.component.ts    From geonetwork-ui with GNU General Public License v2.0 6 votes vote down vote up
currentLayers$ = this.selectedLink$.pipe(
    switchMap((link) => {
      if (!link) {
        return of([])
      }
      this.loading = true
      this.error = null
      return this.getLayerFromLink(link).pipe(
        map((layer) => [layer]),
        catchError((e) => {
          this.error = e.message
          return of([])
        }),
        finalize(() => (this.loading = false))
      )
    })
  )
Example #11
Source File: loader.interceptor.ts    From assetMG with Apache License 2.0 6 votes vote down vote up
intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    this.totalRequests++;
    this.loaderService.show();
    
    return next.handle(req).pipe(
      finalize(() => {
        this.totalRequests--;
        if (this.totalRequests === 0) {
          this.loaderService.hide();
        }
      })
    );
  }
Example #12
Source File: login-in-out.service.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
loginIn(token: string): Promise<void> {
    return new Promise(resolve => {
      this.windowServe.setSessionStorage(TokenKey, TokenPre + token);
      const userInfo: UserInfo = this.userInfoService.parsToken(TokenPre + token);
      // todo  这里是手动添加静态页面标签页操作中,打开详情的按钮的权限,实际操作中可以删除第44行
      userInfo.authCode.push(ActionCode.TabsDetail)
      this.userInfoService.setUserInfo(userInfo);
      this.getMenuByUserId(userInfo.userId).pipe(finalize(()=>{
        resolve();
      })).subscribe(menus => {
        menus = menus.filter(item => {
          item.selected = false;
          item.open = false;
          return item.menuType === 'C';
        });
        const temp = fnFlatDataHasParentToTree(menus);
        this.menuService.setMenuArrayStore(temp);
        resolve();
      })
    })
  }
Example #13
Source File: EntityDataService.ts    From viewer-components-react with MIT License 6 votes vote down vote up
// Convenience method for retrieving all relevant sensor data in one call
  // Returns sensor object, alerts and last observation
  public getDataForSensor$(id: string): Observable<SensorData> {
    if (!this.sensorDataObservables[id]) {
      this.sensorDataObservables[id] = MetricService.getMetrics$([id])
        .pipe(
          switchMap(() => {
            return EntityService.getEntity$(EntityType.SENSOR, id)
              .pipe(
                switchMap((entity: any) => {
                  return combineLatest([
                    AlertService.getActiveAlertsForSensor$(id),
                    this.getObservationQueriesForSensor$(id)
                      .pipe(
                        switchMap((queries: ObservationQuery[]) => {
                          return ObservationService.getLastObservations$(entity, queries);
                        })
                      ),
                  ]).pipe(
                    map(([alerts, observations]: [Alert[], ObservationSet[]]) => {
                      return { sensor: entity, alerts, observations };
                    })
                  );
                })
              );
          }),
          throttleTime(1000, undefined, {leading: true, trailing: true}),
          finalize(() => {
            delete this.sensorDataObservables[id];
          }),
          shareReplay({
            bufferSize: 1,
            refCount: true,
          })
        );
    }

    return this.sensorDataObservables[id];
  }
Example #14
Source File: geolocation.service.ts    From geolocation with MIT License 6 votes vote down vote up
constructor(
        @Inject(GEOLOCATION) geolocationRef: Geolocation,
        @Inject(GEOLOCATION_SUPPORT) geolocationSupported: boolean,
        @Inject(POSITION_OPTIONS)
        positionOptions: PositionOptions,
    ) {
        let watchPositionId = 0;

        super(subscriber => {
            if (!geolocationSupported) {
                subscriber.error('Geolocation is not supported in your browser');
            }

            watchPositionId = geolocationRef.watchPosition(
                position => subscriber.next(position),
                positionError => subscriber.error(positionError),
                positionOptions,
            );
        });

        return this.pipe(
            finalize(() => geolocationRef.clearWatch(watchPositionId)),
            shareReplay({bufferSize: 1, refCount: true}),
        ) as GeolocationService;
    }
Example #15
Source File: indicate.ts    From ngx-operators with MIT License 6 votes vote down vote up
/**
 * Indicates whether the observable is currently loading (meaning subscription is active and
 * it hasn't completed or errored).
 *
 * @param indicator subject as target for indication
 * @returns stream which will indicate loading through passed subject
 */
export function indicate<T>(
  indicator: Subject<boolean>
): (source: Observable<T>) => Observable<T> {
  return (source: Observable<T>) =>
    source.pipe(
      prepare(() => indicator.next(true)),
      finalize(() => indicator.next(false))
    );
}