rxjs/operators#withLatestFrom TypeScript Examples

The following examples show how to use rxjs/operators#withLatestFrom. 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: observables.ts    From webapp with MIT License 6 votes vote down vote up
historicPoolBalances$ = combineLatest([
  unVerifiedPositions$,
  minimalPools$
]).pipe(
  withLatestFrom(currentBlock$),
  switchMapIgnoreThrow(async ([[unverified, minimal], currentBlock]) => {
    const res = await getHistoricBalances(
      unverified,
      currentBlock.blockNumber,
      minimal
    );
    return res;
  })
)
Example #2
Source File: withdraw-button-container.component.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
public ngOnInit(): void {
    this.amountFormControl.valueChanges
      .pipe(
        map(amount => new BigNumber(amount ? amount.split(',').join('') : NaN)),
        withLatestFrom(this.stakingTokenBalance$),
        tap(([amount, stakingTokenBalance]) =>
          this.checkAmountAndBalance(amount, stakingTokenBalance)
        ),
        takeUntil(this.destroy$)
      )
      .subscribe();

    this.walletConnectorService.networkChange$
      .pipe(
        tap(() => {
          if (this.walletConnectorService.networkName !== BLOCKCHAIN_NAME.BINANCE_SMART_CHAIN) {
            this._needChangeNetwork$.next(true);
          } else {
            this._needChangeNetwork$.next(false);
          }
        }),
        takeUntil(this.destroy$)
      )
      .subscribe();
  }
Example #3
Source File: layout-v1-account-horizon-selector.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
horizonValueChanged: Subscription = this.horizonSelectControl
    .valueChanges
    .pipe(withLatestFrom(this.selectedWalletAccount$))
    .pipe(takeUntil(this.componentDestroyed$))
    .subscribe(([horizonId, walletAccount]) => {
      this.horizonApisService.selectHorizonApi(horizonId);

      this.walletsService.selectAccount({
        walletId: walletAccount.walletId,
        publicKey: walletAccount.publicKey,
      });

      this.nzMessageService.success('Horizon selected');
    });
Example #4
Source File: group-options.contextmenu.ts    From RcloneNg with MIT License 6 votes vote down vote up
ngOnInit() {
		const outer = this;
		this.resetStats$ = new (class extends CoreStatsResetFlow {
			public prerequest$: Observable<CombErr<CoreStatsResetFlowInNode>> = outer.resetTrigger.pipe(
				withLatestFrom(outer.cmdService.listCmd$.verify(this.cmd)),
				map(
					([group, cmdNode]): CombErr<CoreStatsResetFlowInNode> => {
						if (cmdNode[1].length !== 0) return [{}, cmdNode[1]] as any;
						if (group && group !== '') return [{ ...cmdNode[0], group }, []];
						return cmdNode;
					}
				)
			);
		})();
		this.resetStats$.deploy();
		this.resetStats$.getSupersetOutput().subscribe(x => {
			let group = x[0] && x[0].group;
			if (!group) group = '[All]';
			if (x[1].length !== 0) {
				this.toastrService.danger(`${group}`, 'Reset stats failure');
				return;
			}
			this.toastrService.success(`${group}`, 'Reset stats success');
		});
	}
Example #5
Source File: carousel.component.ts    From canopy with Apache License 2.0 6 votes vote down vote up
setAutoPlayInterval(): void {
    this.pausableTimer$ = defer(() => {
      return interval(this.autoPlayDelay).pipe(
        takeUntil(this.unsubscribe),
        withLatestFrom(this.pause),
        filter(([ , paused ]) => !paused),
        map(() => this.nextCarouselItem()),
      );
    });

    this.pausableTimer$.subscribe();
    this.cd.detectChanges();
  }
Example #6
Source File: app.effects.ts    From nica-os with MIT License 6 votes vote down vote up
loadAssets$ = createEffect(() => this.actions$.pipe(
    ofType(loadAssets),
    withLatestFrom(
      this.store$.pipe(select(selectLoadedAssets))
    ),
    switchMap(([action, loadedAssets]) => {
      this.store$.dispatch(setLoadingMessage({message: 'Loading website assets.'}));
      if ( loadedAssets ) {
        this.store$.dispatch(setLoadingMessage({message: '<b>Loading</b> done.'}));
        return [loadAssetsSuccess({loadedAssets})];
      } else {
        return this.assetsService.getAll().pipe(
          switchMap(assets => {
            this.store$.dispatch(setLoadingMessage({message: '<b>Loading</b> done.'}));
            return of(assets);
          }),
          delay(2000),
          switchMap(assets => {
            return of(loadAssetsSuccess({loadedAssets: assets}));
          })
        );
      }
    }))
  );
Example #7
Source File: auth.service.ts    From auth0-angular with MIT License 6 votes vote down vote up
/**
   * ```js
   * handleRedirectCallback(url).subscribe(result => ...)
   * ```
   *
   * After the browser redirects back to the callback page,
   * call `handleRedirectCallback` to handle success and error
   * responses from Auth0. If the response is successful, results
   * will be valid according to their expiration times.
   *
   * Calling this method also refreshes the authentication and user states.
   *
   * @param url The URL to that should be used to retrieve the `state` and `code` values. Defaults to `window.location.href` if not given.
   */
  handleRedirectCallback(
    url?: string
  ): Observable<RedirectLoginResult<TAppState>> {
    return defer(() =>
      this.auth0Client.handleRedirectCallback<TAppState>(url)
    ).pipe(
      withLatestFrom(this.authState.isLoading$),
      tap(([result, isLoading]) => {
        if (!isLoading) {
          this.authState.refresh();
        }
        const appState = result?.appState;
        const target = appState?.target ?? '/';

        if (appState) {
          this.appStateSubject$.next(appState);
        }

        this.navigator.navigateByUrl(target);
      }),
      map(([result]) => result)
    );
  }
Example #8
Source File: observables.ts    From webapp with MIT License 6 votes vote down vote up
decimalReserveBalances$ = freshReserveBalances$.pipe(
  withLatestFrom(tokens$),
  map(([pools, tokens]) => {
    const poolsCovered = filterAndWarn(
      pools,
      pool =>
        pool.reserveBalances.every(balance =>
          tokens.some(token => compareString(balance.id, token.dlt_id))
        ),
      "lost reserve balances because it was not covered in API tokens"
    );

    return poolsCovered.map(
      (pool): MinimalPoolWithReserveBalances => ({
        ...pool,
        reserveBalances: pool.reserveBalances.map(reserveBalance => {
          const token = findOrThrow(tokens, token =>
            compareString(token.dlt_id, reserveBalance.id)
          );
          return {
            ...reserveBalance,
            amount: shrinkToken(reserveBalance.amount, token.decimals)
          };
        })
      })
    );
  })
)
Example #9
Source File: superset-flow.ts    From RcloneNg with MIT License 6 votes vote down vote up
protected deployBefore() {
		super.deployBefore();
		this.supersetData$ = this.getOutput().pipe(
			withLatestFrom(this.prerequest$),
			map(([cur, pre]) => this.generateSuperset(cur, pre)),
			shareReplay()
		);
		this.supersetDeployed = true;
	}
Example #10
Source File: effects.ts    From geonetwork-ui with GNU General Public License v2.0 6 votes vote down vote up
loadResults$ = createEffect(() =>
    this.actions$.pipe(
      ofType(REQUEST_MORE_RESULTS),
      // mergeMap is used because of multiple search concerns
      // TODO: should implement our own switchMap to filter by searchId
      mergeMap((action: SearchActions) =>
        this.authService.authReady().pipe(
          withLatestFrom(
            this.store$.pipe(select(getSearchStateSearch, action.id))
          ),
          switchMap(([, state]) =>
            this.searchService.search(
              'bucket',
              JSON.stringify(
                this.esService.getSearchRequestBody(
                  state.config.aggregations,
                  state.params.size,
                  state.params.from,
                  state.params.sortBy,
                  state.config.source,
                  state.params.filters,
                  state.config.filters
                )
              )
            )
          ),
          switchMap((response: EsSearchResponse) => {
            const records = this.esMapper.toRecords(response)
            const aggregations = response.aggregations
            return [
              new AddResults(records, action.id),
              new SetResultsAggregations(aggregations, action.id),
              new SetResultsHits(response.hits.total, action.id),
            ]
          })
        )
      ) // wait for auth to be known
    )
  )
Example #11
Source File: editable.component.ts    From edit-in-place with MIT License 6 votes vote down vote up
private handleViewMode(): void {
    this.viewHandler = fromEvent(this.element, this.openBindingEvent)
      .pipe(
        filter(() => this.enabled),
        withLatestFrom(this.editMode$),
        filter(([_, editMode]) => !editMode),
        takeUntil(this.destroy$)
      )
      .subscribe(() => this.displayEditMode());
  }
Example #12
Source File: util.ts    From ngrx-issue-tracker with MIT License 6 votes vote down vote up
withLatestFromDeferred = <A, B>(other: Observable<B>) =>
  pipe(concatMap((value: A) => of(value).pipe(withLatestFrom(other))))
Example #13
Source File: exampleSlice.ts    From react-native-template with MIT License 6 votes vote down vote up
exampleEpic: MyEpic = (action$: Observable<PayloadAction<undefined>>, state$: Observable<RootStoreType>) =>
    action$.pipe(
        ofType(exampleActions.ping.type, exampleActions.pong.type),
        withLatestFrom(state$),
        map(([action, state]) => {
            console.log(`exampleEpic: I am reacting to ${state.example.globalValue}`)

            // Epics are a stream of actions-in, actions-out
            return { type: 'useless_action' }
        })
    )
Example #14
Source File: settings.effects.ts    From enterprise-ng-2020-workshop with MIT License 6 votes vote down vote up
persistSettings = createEffect(
    () =>
      this.actions$.pipe(
        ofType(
          actionSettingsChangeAnimationsElements,
          actionSettingsChangeAnimationsPage,
          actionSettingsChangeAnimationsPageDisabled,
          actionSettingsChangeAutoNightMode,
          actionSettingsChangeLanguage,
          actionSettingsChangeStickyHeader,
          actionSettingsChangeTheme
        ),
        withLatestFrom(this.store.pipe(select(selectSettingsState))),
        tap(([action, settings]) =>
          this.localStorageService.setItem(SETTINGS_KEY, settings)
        )
      ),
    { dispatch: false }
  );
Example #15
Source File: trade-logs.effects.ts    From zorro-fire-log with MIT License 6 votes vote down vote up
onAddTradeLogs$ = createEffect(() =>
    this.actions$.pipe(
      ofType(addTradeLogs),
      withLatestFrom(this.store.select(selectFilter)),
      map(([action, filter]) => {
        const newFilter = { ...filter };
        const reduced = action.tradeLogs.reduce((acc, cur) => {
          //check alias
          if (!acc.aliases) {
            acc.aliases = {};
          }
          if (!acc.aliases[cur.alias]) {
            acc = {
              ...acc,
              aliases: {
                ...acc.aliases,
                [cur.alias]: { enabled: true, expanded: true, algos: {} },
              },
            };
          }
          if (!acc.aliases[cur.alias].algos[cur.name]) {
            acc.aliases[cur.alias].algos[cur.name] = {
              enabled: true,
              expanded: false,
              symbols: {},
            };
          }
          if (!acc.aliases[cur.alias].algos[cur.name].symbols[cur.asset]) {
            acc.aliases[cur.alias].algos[cur.name].symbols[cur.asset] = {
              enabled: true,
            };
          }
          return acc;
        }, newFilter);
        return updateFilter({ filter: reduced });
      })
    )
  );
Example #16
Source File: map-to-latest-from.ts    From s-libs with MIT License 6 votes vote down vote up
/**
 * Emits the latest value of the given Observable every time the source Observable emits a value.
 *
 * ```
 * source:               -1---2--3------4-|
 * inner:                ---a------b--c---|
 * mapToLastFrom(inner): -----a--a------c-|
 * ```
 */
export function mapToLatestFrom<T>(
  inner$: Observable<T>,
): OperatorFunction<any, T> {
  return flow(
    withLatestFrom(inner$),
    map(([_, inner]) => inner),
  );
}
Example #17
Source File: withdraw-liquidity.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
fetchLiquidityPoolsDataSubscription: Subscription = this.accountBalances$
    .pipe(withLatestFrom(this.horizonApiQuery.getSelectedHorizonApi$))
    .pipe(switchMap(([accountBalances, horizonApi]) => {
      return Promise.all(accountBalances.map(ab => {
        return this.liquidityPoolsService.getLiquidityPoolsData({
          lpId: ab.liquidity_pool_id,
          horizonApi,
        }).catch(e => {
          console.error(e);
          return e;
        });
      }));
    }))
    .pipe(takeUntil(this.componentDestroyed$))
    .subscribe();
Example #18
Source File: stake-button-container.component.ts    From rubic-app with GNU General Public License v3.0 5 votes vote down vote up
public ngOnInit(): void {
    this.amountFormControl.valueChanges
      .pipe(
        startWith(this.amountFormControl.value),
        withLatestFrom(this.selectedTokenBalance$, this.limit$),
        map(([amount, balance, limit]) => {
          const adjustedAmount = new BigNumber(amount ? amount.split(',').join('') : NaN);

          return [adjustedAmount, balance, limit];
        }),
        tap(([amount, balance, limit]) => {
          this.checkAmountAndBalance(amount as BigNumber, balance as BigNumber, limit as Limits);
          if (this.isUserWhitelisted) {
            this.checkAmountAndBalanceWhitelist(
              amount as BigNumber,
              balance as BigNumber,
              limit as Limits
            );
          }
        }),
        withLatestFrom(this.selectedToken$),
        switchMap(([[amount, balance, limit], selectedToken]) => {
          return zip(
            selectedToken.blockchain !== BLOCKCHAIN_NAME.BINANCE_SMART_CHAIN
              ? of(false)
              : this.stakingService.needApprove(amount as BigNumber),
            of(balance),
            of(limit),
            of(amount)
          );
        }),
        tap(([needApprove, balance, limit, amount]) => {
          this._needApprove$.next(needApprove);
          this.checkAmountAndBalance(amount as BigNumber, balance as BigNumber, limit as Limits);

          if (this.stakingService.isUserWhitelisted) {
            this.checkAmountAndBalanceWhitelist(
              amount as BigNumber,
              balance as BigNumber,
              limit as Limits
            );
          }
        }),
        takeUntil(this.destroy$)
      )
      .subscribe();
  }
Example #19
Source File: claimable-balance-details.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
claimant$ = this.claimableBalance$
    .pipe(withLatestFrom(this.walletsAccountsQuery.getSelectedAccount$))
    .pipe(map(([claimableBalance, selectedAccount]) => {
      return claimableBalance?.claimants.find(claimant => {
        return claimant.destination === selectedAccount.publicKey;
      });
    }));
Example #20
Source File: projects.effects.ts    From nuxx with GNU Affero General Public License v3.0 5 votes vote down vote up
@Effect()
  SaveProject$ = this.actions$.pipe(
    ofType(ProjectActions.SAVE_PROJECT),
    withLatestFrom(this.store.select('project')),
    switchMap(([action, payload]) => {
      const currentProject = {
        name: payload.name ? payload.name : `New project`,
        data: {
          canvas: payload.canvas,
          version: payload.version,
          volumes: payload.volumes,
          services: payload.services,
          networks: payload.networks,
          secrets: payload.secrets,
        },
      }

      if (payload.uuid && payload.mutable) {
        return this.restService.saveProject(currentProject, payload.uuid).pipe(
          map((projectData) => {
            const project = {
              name: projectData.name,
              mutable: projectData.mutable,
              ...projectData.data,
            }
            return ProjectActions.SaveProjectSuccess({ data: project })
          }),
          catchError((error) => of(ProjectActions.ApiProjectRequestFail({ data: error }))),
        )
      } else {
        return this.restService.createProject(currentProject).pipe(
          map((projectData) => {
            const project = {
              name: projectData.name,
              uuid: projectData.uuid,
              mutable: projectData.mutable,
              ...projectData.data,
            }
            window.location.href = `/${projectData.uuid}`
            return ProjectActions.SaveProjectSuccess({ data: project })
          }),
          catchError((error) => of(ProjectActions.ApiProjectRequestFail({ data: error }))),
        )
      }
    }),
  )
Example #21
Source File: deposit-liquidity.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
availableAssetBFunds$ = this.assetB$
    .pipe(withLatestFrom(this.selectedAccount$))
    .pipe(map(([selectedAsset, selectedAccount]) => {
      return this.calculateAvailableFunds(selectedAsset, selectedAccount);
    }));
Example #22
Source File: form-tree-node.service.ts    From open-source with MIT License 5 votes vote down vote up
setupListeners(): void {
    if (!this.isFormLoaded) {
      this.logger.setupListeners(this);
      this._formLoaded = true;

      // listen control changes to update the error
      merge(
        this._control.valueChanges,
        this._control.statusChanges,
      ).pipe(
        takeUntil(this._unsubscribe),
        debounceTime(20), // wait for subcontrols to be updated
        map(() => this._control.errors),
        distinctUntilChanged(),
        withLatestFrom(this._errorMsg$),
      ).subscribe(([_, currentError]) => {
        if (this._control.valid) {
          // reset any existing error
          if (currentError) {
            this._errorMsg$.next(null);
          }
        } else {
          // update the error message if needed
          const errorMsg = this.getErrorMessage();
          if (currentError !== errorMsg) {
            this._errorMsg$.next(errorMsg);
          }
        }
      });

      // process the stored matchers
      this._matchers?.map((config) => {
        const matchers = config.matchers.map(matcher => this.formHandlers.getMatcher(matcher));
        let count = 0;

        combineLatest(
          // build an array of observables to listen changes into
          config.when
            .map(condition => this.formHandlers.getCondition(condition)) // handler fn
            .map(fn => fn(this)) // condition observables
        ).pipe(
          map<any[], { hasMatch: boolean, results: any[] }>(results => ({
            hasMatch: config.operator === 'OR' // AND by default
              ? results.some(Boolean)
              : results.every(Boolean),
            results,
          })),
          takeUntil(this._unsubscribe),
          // TODO option for distinctUntilChanged?
        )
        .subscribe(({ hasMatch, results }) => {
          const firstTime = (count === 0);
          // run the matchers with the conditions result
          // TODO config to run the matcher only if hasMatch? (unidirectional)
          matchers.map(matcher => matcher({
            node: this,
            hasMatch: config.negate ? !hasMatch : hasMatch,
            firstTime,
            results,
          }));
          count++;
        });
      });
    }

    // call the children
    this.children.map(child => child.setupListeners());
  }
Example #23
Source File: initiate-search.ts    From js-client with MIT License 5 votes vote down vote up
QUERY_INIT_RESULTS: Observable<{
	requestID: string;
	msg: RawSearchInitiatedMessageReceived;
}> = QUERY_QUEUE.pipe(
	// When a "request" is received, create an Observable to listen to incoming RawSearchInitiatedMessageReceived,
	// and send a RawInitiateSearchMessageSent when ready. concatMap ensures we only have one sender/listener at a time.
	// We won't send the next request until we've heard a response for the current request.
	concatMap(({ requestID, rawSubscription, query, options }) =>
		// Listen for incoming messages on the search websocket
		rawSubscription.received$.pipe(
			withLatestFrom(
				// Wait to send RawInitiateSearchMessageSent until concatMap has subscribed to the outer Observable
				defer(() => {
					return rawSubscription.send(<RawInitiateSearchMessageSent>{
						type: 'search',
						data: {
							Addendum: options.initialFilterID ? { filterID: options.initialFilterID } : {},
							Background: false,
							Metadata: options.metadata ?? {},
							SearchStart: options.range === 'preview' ? null : options.range?.[0]?.toISOString() ?? null,
							SearchEnd: options.range === 'preview' ? null : options.range?.[1]?.toISOString() ?? null,
							SearchString: query,
							Preview: options.range === 'preview',
							NoHistory: options.noHistory ?? false,
						},
					});
				}),
			),
			// Discard the (void) result from rawSubscription.send(). We only need the messages coming from received$
			map(([msg]) => msg),

			// Filter to only RawSearchInitiatedMessageReceived messages
			filter((msg): msg is RawSearchInitiatedMessageReceived => {
				try {
					const _msg = <RawSearchInitiatedMessageReceived>msg;

					// the type is about all we can count on -- in Error cases, Metadata and Addendum are unavailable.
					return _msg.type === 'search';
				} catch {
					return false;
				}
			}),

			// There's only one Received per Sent, so we're done after the first
			first(),

			// Include the internal "request" ID
			map(msg => ({ requestID, msg })),
		),
	),
	share(),
)
Example #24
Source File: clean-finished-groups.dialog.ts    From RcloneNg with MIT License 5 votes vote down vote up
ngOnInit() {
		const outer = this;
		const trigger = new Subject();
		const listGroup$ = new (class extends ListGroupFlow {
			public prerequest$ = trigger.pipe(
				withLatestFrom(outer.cmdService.listCmd$.verify(this.cmd)),
				map(x => x[1])
			);
		})();
		listGroup$.deploy();
		const stats$ = new (class extends CoreStatsFlow {
			public prerequest$ = trigger.pipe(
				withLatestFrom(outer.cmdService.listCmd$.verify(this.cmd)),
				map(x => x[1])
			);
		})();
		stats$.deploy();

		this.loading = true;
		listGroup$.clearCache();
		stats$.clearCache();
		zip(listGroup$.getOutput(), stats$.getOutput()).subscribe(([list, stats]) => {
			this.loading = false;
			if (list[1].length !== 0 || stats[1].length !== 0) return;
			const transferring = stats[0]['core-stats'].transferring;
			this.finishedGroup = !transferring
				? list[0].groups
				: list[0].groups.filter(x => !transferring.some(y => x === y.group));
			this.check = this.finishedGroup.map(() => true);
		});
		trigger.next();

		this.deleteStates$ = new (class extends CoreStatsDeleteFlow {
			public prerequest$: Observable<CombErr<CoreStatsDeleteFlowInNode>> = outer.deleteTrigger.pipe(
				withLatestFrom(outer.cmdService.listCmd$.verify(this.cmd)),
				switchMap(([groups, y]) => {
					if (y[1].length !== 0) return of([{}, y[1]] as any);
					return of(...groups.map(group => [{ ...y[0], group }, []]));
				}),
				// TODO: need a tasks queue
				concatMap(x => of(x).pipe(delay(1000)))
			);
		})();
		this.deleteStates$.deploy();
		this.deleteStates$.getOutput().subscribe();
	}
Example #25
Source File: lp-asset-item.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
ngOnInit(): void {
    this.lpAsset$
      .pipe(filter<any>(Boolean))
      .pipe(take(1))
      .pipe(withLatestFrom(this.horizonApisQuery.getSelectedHorizonApi$))
      .pipe(switchMap((data: [ILpAsset, IHorizonApi]) => {
        return this.liquidityPoolsService.getLiquidityPoolsData({
          lpId: data[0]._id,
          horizonApi: data[1],
        });
      }))
      .pipe(takeUntil(this.componentDestroyed$))
      .subscribe();


    this.lpAsset$
      .pipe(filter<any>(Boolean))
      .pipe(take(1))
      .pipe(pluck<ILpAssetLoaded, ILpAssetLoaded['reserves']>('reserves'))
      .pipe(filter<any>(Boolean))
      .pipe(map((reserves: ILpAssetLoaded['reserves']) => {
        const mappedData = reserves
          .reduce((all: { [x: string]: Horizon.Reserve }, current: Horizon.Reserve) => {
            if (current.asset !== 'native' && !all[current.asset]) {
              all[current.asset] = current;
            }

            return all;
          }, {});

        return Object.values(mappedData);
      }))
      .pipe(mergeMap(reserve => reserve))
      .pipe(withLatestFrom(this.horizonApisQuery.getSelectedHorizonApi$))
      .pipe(takeUntil(this.componentDestroyed$))
      .subscribe(([reserve, horizonApi]) => {
        const assetCode = reserve.asset.split(':')[0] as string;
        const assetIssuer = reserve.asset.split(':')[1] as string;

        this.walletsAssetsService.saveInitialAssetState({
          _id: `${assetCode}_${assetIssuer}`,
          assetCode,
          assetIssuer,
          networkPassphrase: horizonApi.networkPassphrase,
        });

        this.walletsAssetsService.requestAssetData$.next({
          _id: `${assetCode}_${assetIssuer}`,
          assetCode,
          assetIssuer,
          horizonApi,
        });
      });
  }
Example #26
Source File: file.detail.ts    From RcloneNg with MIT License 5 votes vote down vote up
ngOnInit() {
		const outer = this;
		this.loadingAbout = true;
		const fsinfo$ = new (class extends OperationsFsinfoFlow {
			public prerequest$ = combineLatest([
				outer.aboutTrigger,
				outer.cmdService.listCmd$.verify(this.cmd),
			]).pipe(
				map(
					([navNode, cmdNode]): CombErr<OperationsFsinfoFlowInNode> => {
						if (cmdNode[1].length !== 0) return [{}, cmdNode[1]] as any;
						return [{ ...cmdNode[0], ...navNode }, []];
					}
				)
			);
		})();
		fsinfo$.deploy();
		fsinfo$.getOutput().subscribe(x => {
			if (x[1].length !== 0) return;
			const fsinfo = x[0]['fs-info'];
		});
		this.about$ = new (class extends OperationsAboutFlow {
			public prerequest$ = fsinfo$.getSupersetOutput();
		})();
		this.about$.deploy();
		this.about$.getOutput().subscribe(x => {
			this.loadingAbout = false;
			if (x[1].length !== 0) return;
			this.chart.data = x[0].about;
		});
		this.downloadTrigger
			.pipe(withLatestFrom(this.serverSettingService.options$.getOutput()))
			.subscribe(([, optionsNode]) => {
				if (NestedGet(optionsNode[0].options, 'rc', 'Serve'))
					this.modal
						.confirm()
						.className('flat-attack')
						.message(`Are you sure want to download ${this.name} ?`)
						.isBlocking(false)
						.open()
						.result.then(
							x => {
								if (x) this.realDownload();
							},
							() => {}
						);
				else {
					this.modal
						.open(
							this.EnableServe,
							overlayConfigFactory({ isBlocking: false, className: 'flat-attack' }, VEXModalContext)
						)
						.result.then(
							x => {
								if (x) {
									this.serverSettingService.setOption({ rc: { Serve: true } });
									this.toastrService.default('Download', 'Try to download again.');
								}
							},
							() => {}
						);
				}
			});
		if (this.initNode)
			setTimeout(() => {
				this.itemNode(this.initNode);
			}, 100);
	}
Example #27
Source File: route.component.ts    From router with MIT License 5 votes vote down vote up
ngOnInit(): void {
    // account for root level routes, don't add the basePath
    const path = this.routerComponent.parentRouterComponent
      ? this.routerComponent.parentRouterComponent.basePath + this.path
      : this.path;

    this.route = this.registerRoute(path, this.exact, this.load);

    this.routerComponent.activeRoute$
      .pipe(
        filter((ar) => ar !== null),
        distinctUntilChanged(),
        withLatestFrom(this.shouldRender$),
        mergeMap(([current, rendered]) => {
          if (current.route === this.route) {
            if (this.redirectTo) {
              this.router.go(this.redirectTo);
              return of(null);
            }

            this.updateState({
              params: current.params,
              path: current.path,
            });

            if (!rendered) {
              if (!this.reuse) {
                this.clearView();
              }

              return this.loadAndRender(current.route);
            }

            return of(null);
          } else if (rendered) {
            return of(this.clearView());
          }

          return of(null);
        }),
        takeUntil(this.destroy$)
      )
      .subscribe();
  }
Example #28
Source File: send-payment.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
selectedAsset$ = this.form.controls.assetCode.valueChanges
    .pipe(shareReplay(1))
    .pipe(withLatestFrom(this.heldAssets$))
    .pipe(map(([assetId, heldAssets]) => {
      return heldAssets.find(({ _id }) => assetId === _id);
    }));