rxjs/operators#shareReplay TypeScript Examples

The following examples show how to use rxjs/operators#shareReplay. 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: gas-settings.component.ts    From gnosis.1inch.exchange with MIT License 6 votes vote down vote up
ngOnInit(): void {

    this.gasPrice$ = this.txSpeedSelect.valueChanges.pipe(
      switchMap((txSpeed: TxSpeed) => {
        console.log(`txSpeed=`, txSpeed);
        if (txSpeed !== 'custom') {
          return of(this.getGasPrice(txSpeed));
        }

        return this.gasPriceInput.valueChanges.pipe(
            startWith(this.gasPriceInput.value),
            filter(() => !this.gasPriceInput.errors),
            map((value) => {
              this.customGasPrice = value;
              return [formatGasPrice(value), value];
            })
          );

      }),
      map(([gasPriceBN, gasPrice]) => {
        this.gasPriceChange.next({
          gasPriceBN,
          gasPrice,
          txSpeed: this.txSpeedSelect.value
        });
        return gasPrice;
      }),
      shareReplay({ bufferSize: 1, refCount: true })
    );

    this.subscription.add(
      this.gasPrice$.subscribe()
    );
  }
Example #2
Source File: bare-flow.ts    From RcloneNg with MIT License 6 votes vote down vote up
protected deployBefore() {
		this.bareData$ = this.prerequest$.pipe(
			switchMap(
				(pre): Observable<CombErr<Tout>> => {
					if (pre[1].length === 0) return this.request(pre).pipe(take(1));
					return of((pre as any) as CombErr<Tout>); // force to convert. There are some errors at privious flow.
					// Just make sure that checking Error[] at first in subscription
				}
			),
			shareReplay()
		);
		this.deployed = true;
	}
Example #3
Source File: auth.store.ts    From reactive-angular-course with MIT License 6 votes vote down vote up
login(email:string, password:string): Observable<User> {
        return this.http.post<User>("/api/login", {email, password})
            .pipe(
                tap(user => {
                    this.subject.next(user);
                    localStorage.setItem(AUTH_DATA, JSON.stringify(user));
                }),
                shareReplay()
            );
    }
Example #4
Source File: contracts.ts    From webapp with MIT License 6 votes vote down vote up
contractAddresses$ = networkVars$.pipe(
  switchMapIgnoreThrow(networkVariables => {
    return fetchContractAddresses(networkVariables.contractRegistry).catch(() =>
      vxm.ethBancor.fetchContractAddresses(networkVariables.contractRegistry)
    );
  }),
  tap(x => {
    if (vxm && vxm.ethBancor) {
      vxm.ethBancor.setContractAddresses(x);
    }
  }),
  distinctUntilChanged<RegisteredContracts>(isEqual),
  shareReplay(1)
)
Example #5
Source File: auth.service.ts    From bitcoin-s-ts with MIT License 6 votes vote down vote up
refresh() {
    const refreshToken = localStorage.getItem(REFRESH_TOKEN_KEY)
    if (!refreshToken) {
      console.error('no refreshToken to refresh')
      return of(<LoginResponse><unknown>null)
    }
    return this.http.post<LoginResponse>(environment.proxyApi + `/auth/refresh`, 
      { user: 'frontend', refreshToken })
      .pipe(catchError(error => {
        this.doLogout()
        throw(Error('auth refresh error, doLogout()'))
      }), tap(res => {
        this.setSession(res)
      }), shareReplay())
  }
Example #6
Source File: email.service.ts    From careydevelopmentcrm with MIT License 6 votes vote down vote up
fetchInbox(refresh?: boolean): Observable<Email[]> {
    let url = `${baseUrl}/email/inbox`; 
    console.log("Fetch inbox URL is " + url);

    if (!this.emailMessagesRequest$ || refresh) {
      this.emailMessagesRequest$ = this.http.get<Email[]>(url).pipe(
        shareReplay(1)
      );
    }

    return this.emailMessagesRequest$;
  }
Example #7
Source File: fetch.ts    From firebase-tools-ui with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if realtime is possible at the node. Only checks once for the current
 * node.
 */
export function canDoRealtime(
  realtimeRef: firebase.database.Reference
): Observable<boolean> {
  const silent = restUrl(realtimeRef, {
    print: 'silent',
    timeout: REST_TIMEOUT,
  });
  return defer(() => fetch(silent, { headers: ADMIN_AUTH_HEADERS })).pipe(
    mapTo(true),
    catchError(() => of(false)),
    shareReplay({ bufferSize: 1, refCount: true })
  );
}
Example #8
Source File: sign-in.page.ts    From fyle-mobile-app with MIT License 6 votes vote down vote up
async checkIfEmailExists() {
    if (this.fg.controls.email.valid) {
      this.emailLoading = true;

      const checkEmailExists$ = this.routerAuthService.checkEmailExists(this.fg.controls.email.value).pipe(
        catchError((err) => {
          this.handleError(err);
          return throwError(err);
        }),
        shareReplay(1),
        finalize(async () => {
          this.emailLoading = false;
        })
      );

      const saml$ = checkEmailExists$.pipe(filter((res) => (res.saml ? true : false)));

      const basicSignIn$ = checkEmailExists$.pipe(filter((res) => (!res.saml ? true : false)));

      basicSignIn$.subscribe(() => {
        this.emailSet = true;
      });

      saml$.subscribe((res) => {
        this.handleSamlSignIn(res);
      });
    } else {
      this.fg.controls.email.markAsTouched();
    }
  }
Example #9
Source File: data-view-table.component.ts    From geonetwork-ui with GNU General Public License v2.0 6 votes vote down vote up
tableData$ = combineLatest([
    this.compatibleDataLinks$,
    this.selectedLinkIndex$.pipe(distinctUntilChanged()),
  ]).pipe(
    map(([links, index]) => links[index]),
    switchMap((link) => {
      this.loading = true
      this.error = null
      return link
        ? this.fetchData(link).pipe(
            catchError((error) => {
              this.error = error.message
              return of([])
            }),
            finalize(() => {
              this.loading = false
            })
          )
        : of([])
    }),
    shareReplay(1)
  )
Example #10
Source File: client.ts    From js-client with MIT License 6 votes vote down vote up
private readonly _context$: Observable<APIContext> = combineLatest(
		this.host$,
		this.useEncryption$,
		this.authToken$,
	).pipe(
		map(([host, useEncryption, authToken]) => ({
			host,
			useEncryption,
			authToken,
			fetch: this._initialOptions.fetch ?? fetch,
		})),
		distinctUntilChanged((a, b) => isEqual(a, b)),
		shareReplay(1),
	);
Example #11
Source File: AlertService.ts    From viewer-components-react with MIT License 6 votes vote down vote up
private subscribeToAlertChangesForSensor$(sensorId: string): Observable<void> {

    // First, check if we need to set up a global alert triggers subscription
    if (!this.alertTriggersSubscription) {
      this.alertTriggersSubscription = SocketService.send$(this.socketEndpoints.subscribeAlertTriggers)
        .pipe(
          // tap((data: any) => LoggerService.log("Received new alert triggers:", data)),
          shareReplay(0)
        );
    }

    // Next, return an Observable that filters the global alert trigger subscription based on current sensorId
    return this.alertTriggersSubscription.pipe(
      filter((data: any) => {

        let triggerForCurrentSensor = false;

        // Status alert trigger check
        if (data.entities && data.entities.includes(sensorId)) {
          triggerForCurrentSensor = true;
        }

        // Data alert trigger check
        if (data.context && !triggerForCurrentSensor) {
          _forEach(data.context, (trigger: any) => {
            if (trigger.sensorId === sensorId) {
              triggerForCurrentSensor = true;
            }
          });
        }

        return triggerForCurrentSensor;
      }),
      map(() => void 0),
      throttleTime(1000, undefined, {leading: true, trailing: true})
    );
  }
Example #12
Source File: map-util.service.ts    From EDA with GNU Affero General Public License v3.0 6 votes vote down vote up
initShapes(mapID: string): void {
        if (!this.mapsObservables$[mapID]) {
            this.mapsObservables$[mapID] = this.get(`${this.route}/${mapID}`).pipe(
                shareReplay(1)
            );
        }
    }
Example #13
Source File: form-tree-node.service.ts    From open-source with MIT License 6 votes vote down vote up
loaded$: Observable<boolean> = this._children$.pipe(
    startWith(null),
    switchMap(() => combineLatest([
      this._numChild$,
      this._loaded$,
      this._paramsLoaded$,
      ...this.children.map(child => child.loaded$),
    ])),
    map(([children, loadedComponent, loadedParams, ...childrenLoaded]) => {
      const isControl = this.instance === DynInstanceType.Control;
      const hasAllChildren = children === childrenLoaded.length;
      const allChildrenValid = childrenLoaded.every(Boolean);
      const allChildrenLoaded = this.instance === DynInstanceType.Control ? true : hasAllChildren && allChildrenValid;

      const result = Boolean(loadedComponent && loadedParams) && allChildrenLoaded;

      this.logger.nodeLoad(this, !isControl
        ? { loaded$: result, loadedComponent, loadedParams, children, childrenLoaded }
        : { loaded$: result, loadedComponent, loadedParams }
      );

      return result;
    }),
    distinctUntilChanged(),
    shareReplay(1),
  );
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: capture-transactions.component.ts    From capture-lite with GNU General Public License v3.0 6 votes vote down vote up
readonly transactionsWithStatus$ =
    this.diaBackendTransactionRepository.all$.pipe(
      take(1),
      map(transactions =>
        transactions.results.map(transaction => ({
          ...transaction,
          status: getStatus(transaction, this.diaBackendAuthService.getEmail()),
        }))
      ),
      catchError((err: unknown) => {
        this.errorService.toastError$(err).subscribe();
        return of([]);
      }),
      finalize(() => this.isFetching$.next(false)),
      shareReplay({ bufferSize: 1, refCount: true })
    );
Example #16
Source File: app.logic.ts    From client-side-databases with Apache License 2.0 6 votes vote down vote up
constructor() {
        const userChangedSubject$ = new Subject();
        DataStore.observe(AWSUser as any).subscribe(user => {
            userChangedSubject$.next(user);
        });
        this.userChanged$ = userChangedSubject$.asObservable().pipe(
            startWith(1),
            shareReplay()
        );

        const messageChangedSubject$ = new Subject();
        DataStore.observe(AWSMessage as any).subscribe(user => {
            messageChangedSubject$.next(user);
        });
        this.messageChanged$ = messageChangedSubject$.asObservable().pipe(
            startWith(1),
            shareReplay()
        );
    }
Example #17
Source File: photo.page.ts    From ionic-pwa-example-moment with MIT License 6 votes vote down vote up
readonly address$ = combineLatest([
    this.geolocationPosition$,
    this.languagesService.language$,
  ]).pipe(
    switchMap(([position, language]) =>
      this.httpClient.get<FeatureCollection>(
        `https://nominatim.openstreetmap.org/reverse?lat=${position.latitude}&lon=${position.longitude}&format=geojson&accept-language=${language}`
      )
    ),
    map(json => {
      if (json.features.length === 0) return undefined;
      const properties = json.features[0].properties;
      if (!properties) return undefined;
      return properties['display_name'] as string | undefined;
    }),
    shareReplay({ bufferSize: 1, refCount: true })
  );
Example #18
Source File: preview.web.service.ts    From sba-angular with MIT License 6 votes vote down vote up
/**
     * Gets {@link PreviewData} for a document in the context of a {@link IQuery}
     *
     * @param id The document id
     * @param query The query context
     * @param auditEvents Audit events to store on the server
     */
    public get(id: string, query: IQuery, auditEvents?: AuditEvents): Observable<PreviewData> {
        return this.httpClient.post<PreviewData>(this.makeUrl("preview"), {
            app: this.appName,
            action: "get",
            id,
            query,
            browserUrl: this.startConfig.browserUrl,
            $auditRecord: auditEvents
        }).pipe(shareReplay(1));
    }
Example #19
Source File: ngx-mat-timepicker-base.directive.ts    From ngx-mat-timepicker with MIT License 6 votes vote down vote up
ngOnInit(): void {
        this._defineTime();
        this.selectedHour = this._timepickerSrv.selectedHour
            .pipe(shareReplay({bufferSize: 1, refCount: true}));
        this.selectedMinute = this._timepickerSrv.selectedMinute
            .pipe(shareReplay({bufferSize: 1, refCount: true}));
        this.selectedPeriod = this._timepickerSrv.selectedPeriod
            .pipe(shareReplay({bufferSize: 1, refCount: true}));
        this.data.timepickerBaseRef.timeUpdated.pipe(takeUntil(this._subsCtrl$))
            .subscribe(this._setDefaultTime.bind(this));
    }
Example #20
Source File: app.component.ts    From gnosis.1inch.exchange with MIT License 5 votes vote down vote up
constructor(
        private oneInchApiService: OneInchApiService,
        private gnosisService: GnosisService,
        private tokenPriceService: TokenPriceService,
        public tokenService: TokenService,
        private ethereumService: EthereumService,
        iconRegistry: MatIconRegistry,
        sanitizer: DomSanitizer
    ) {

        iconRegistry.addSvgIcon('settings', sanitizer.bypassSecurityTrustResourceUrl('assets/settings.svg'));
        iconRegistry.addSvgIcon('swap', sanitizer.bypassSecurityTrustResourceUrl('assets/swap.svg'));

        // need to subscribe before addListener
        this.gnosisService.walletAddress$.subscribe();
        // this.gnosisService.isMainNet$.subscribe(console.log);

        this.sortedTokens$ = this.gnosisService.walletAddress$.pipe(
            switchMap((walletAddress) => {
                return combineLatest([
                    this.tokenService.getSortedTokens(walletAddress),
                    this.tokenService.tokenHelper$
                ]);
            }),
            map(([tokens, tokenHelper]) => {

                this.updateFromAmountValidator(tokenHelper);
                this.openLoader = false;
                return tokens;
            }),
            shareReplay({bufferSize: 1, refCount: true})
        );

        this.filteredFromTokens$ = this.getFilteredTokens(this.autoCompleteCtrlFromToken);
        this.filteredToTokens$ = this.getFilteredTokens(this.autoCompleteCtrlToToken);

        this.swapForm.controls.fromAmount.setValue(this.fromAmount, {emitEvent: false});

        const fromAmountChange$ = this.swapForm.controls.fromAmount.valueChanges.pipe(
            startWith(this.fromAmount),
            debounceTime(200),
            distinctUntilChanged(),
            map((value: string) => ({
                fromAmount: value,
                resetFields: true
            }))
        );

        const fromAmountListener$ = merge(fromAmountChange$, this.updateAmounts.asObservable())
            .pipe(
                switchMap((({fromAmount}) => {
                    return this.setAmounts(fromAmount).pipe(
                        // background refresh
                        repeatWhen((completed) => completed.pipe(delay(20000)))
                    );
                }))
            );

        this.subscription.add(fromAmountListener$.subscribe());
        this.gnosisService.addListeners();
    }
Example #21
Source File: withdraw-liquidity.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
selectedLiquidityPool$: Observable<ILpAssetLoaded> = this.withDrawForm.controls.selectedPoolId
    .valueChanges
    .pipe(shareReplay(1))
    .pipe(switchMap(selectedPoolId =>
      this.lpAssetsQuery.selectEntity(selectedPoolId) as Observable<ILpAssetLoaded>
    ));
Example #22
Source File: product.service.ts    From Angular-ActionStreams with MIT License 5 votes vote down vote up
// List of products
  allProducts$ = this.http.get<Product[]>(this.productsUrl)
    .pipe(
      tap(response => console.log(JSON.stringify(response))),
      shareReplay(1),
      catchError(this.handleError)
    );
Example #23
Source File: product.service.ts    From Angular-HigherOrderMapping with MIT License 5 votes vote down vote up
// List of products
  products$ = this.http.get<ProductResponse>(this.productListUrl)
    .pipe(
      tap(response => console.log(JSON.stringify(response))),
      map(response => response.data),
      shareReplay(1),
      catchError(this.handleError)
    );
Example #24
Source File: travel-tabs.component.ts    From travel-list with MIT License 5 votes vote down vote up
refresh() {
    const api$ = this.apiService.getTravels$().pipe(shareReplay(1));

    this.tabs = [...this.tabs.map(x => ({
      ...x,
      data: api$.pipe(map(travel => travel[x.title.toLowerCase()]))
    }))];
  }
Example #25
Source File: courses.service.ts    From reactive-angular-course with MIT License 5 votes vote down vote up
loadCourseById(courseId:number) {
       return this.http.get<Course>(`/api/courses/${courseId}`)
            .pipe(
              shareReplay()
            );
    }
Example #26
Source File: auth.state.ts    From auth0-angular with MIT License 5 votes vote down vote up
/**
   * Emits boolean values indicating the authentication state of the user. If `true`, it means a user has authenticated.
   * This depends on the value of `isLoading$`, so there is no need to manually check the loading state of the SDK.
   */
  readonly isAuthenticated$ = this.isAuthenticatedTrigger$.pipe(
    distinctUntilChanged(),
    shareReplay(1)
  );
Example #27
Source File: auth.ts    From webapp with MIT License 5 votes vote down vote up
onLogin$ = onLoginNoType$.pipe(
  map(currentUser => currentUser as string),
  shareReplay(1)
)