rxjs#Observable TypeScript Examples
The following examples show how to use
rxjs#Observable.
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: app.component.ts From gnosis.1inch.exchange with MIT License | 7 votes |
private getFilteredTokens(form: FormControl): Observable<ITokenDescriptor[]> {
return combineLatest([
this.sortedTokens$,
form.valueChanges.pipe(
startWith('')
),
]).pipe(
map((x) => {
const [tokens, filterText] = x;
return filterTokens(tokens, filterText);
})
);
}
Example #2
Source File: sign-xdr.component.ts From xBull-Wallet with GNU Affero General Public License v3.0 | 6 votes |
// TODO: Make this dynamic with a config store
fee$: Observable<string> = this.xdrParsed$
.pipe(filter<Transaction>(data => !!data))
.pipe(pluck<Transaction, string>('fee'))
.pipe(map(fee =>
new BigNumber(fee)
.dividedBy('10000000')
.toString()
));
Example #3
Source File: 1inch.api.service.ts From gnosis.1inch.exchange with MIT License | 6 votes |
public getQuote$(
fromTokenAddress: string,
toTokenAddress: string,
amount: string,
): Observable<Quote> {
let params = new HttpParams();
params = params.append('fromTokenAddress', fromTokenAddress);
params = params.append('toTokenAddress', toTokenAddress);
params = params.append('amount', amount);
const url = this.url + '/quote';
return this.http.get<Quote>(url, { params }).pipe(
delayedRetry(1000)
);
}
Example #4
Source File: alerts-labels.service.ts From xBull-Wallet with GNU Affero General Public License v3.0 | 6 votes |
getAlertsLabelsByCreitTech(): Observable<IAlertsLabel[]> {
this.alertsLabelsStore.updateUIState({ gettingAlertsLabelsByCreitTech: true });
return this.http.get<{ items: IAlertsLabel[] }>(`https://raw.githubusercontent.com/Creit-Tech/stellar-assets/main/dist/alert-labels-by-creit-tech.json`)
.pipe(map(response => {
const alertsLabels = response.items.map(item => createAlertsLabel(item));
applyTransaction(() => {
this.alertsLabelsStore.updateUIState({ gettingAlertsLabelsByCreitTech: false });
this.alertsLabelsStore.upsertMany(alertsLabels);
});
return alertsLabels;
}));
}
Example #5
Source File: erc20.helper.ts From gnosis.1inch.exchange with MIT License | 6 votes |
public isTokenApproved(
tokenAddress: string,
walletAddress: string,
spender: string,
amount: BigNumber
): Observable<boolean> {
if (ethAddresses.indexOf(tokenAddress) !== -1) {
return of(true);
}
return this.getApprovedAmount(
tokenAddress,
walletAddress,
spender
).pipe(
map((approvedAmount) => approvedAmount.gte(amount)),
take(1)
);
}
Example #6
Source File: wallet-dashboard.component.ts From xBull-Wallet with GNU Affero General Public License v3.0 | 6 votes |
sizeOfPortfolioGraphValues$: Observable<Array<{ name?: string; value: number }>> = this.accountBalancesRegularAssets$
.pipe(map(balances => {
const totalBalanceOfAssets = balances.reduce((total, current) => {
return new BigNumber(current.balance).plus(total);
}, new BigNumber(0));
return balances.map(b => {
const balanceLineId = this.walletsAssetsService.formatBalanceLineId(b);
const asset = this.walletsAssetsService.sdkAssetFromAssetId(balanceLineId);
return {
name: asset.code || '',
value: new BigNumber(b.balance).dividedBy(totalBalanceOfAssets).multipliedBy(100).toNumber(),
};
});
}));
Example #7
Source File: ethereum.service.ts From gnosis.1inch.exchange with MIT License | 6 votes |
public getBalance(
walletAddress: string,
contractAddress = ethAddresses[0],
blockNumber?: number
): Observable<BigNumber> {
if (ethAddresses.indexOf(contractAddress) === -1) {
return this.getErc20Balance(
contractAddress,
walletAddress,
blockNumber
);
}
return this.web3Service.web3$.pipe(
mergeMap((web3) => {
const call$ = web3.eth.getBalance(
walletAddress,
blockNumber || 'latest'
).then((bal) => {
return BigNumber.isBigNumber(bal) ? bal : bigNumberify(bal);
});
return fromPromise(call$) as Observable<BigNumber>;
}),
catchError(() => {
return of(zeroValueBN);
}),
take(1)
);
}
Example #8
Source File: wallet-dashboard.component.ts From xBull-Wallet with GNU Affero General Public License v3.0 | 6 votes |
// ----- Graphs
balanceGraphValues$: Observable<Array<{ name?: string; value: number }>> = this.assetsBalancesWithCounterValues$
.pipe(withLatestFrom(this.totalBalanceOnCounterAsset$))
.pipe(map(([values, totalBalanceOnCounterAsset]) => values.map(value => {
return {
name: value.asset?.assetCode || '',
value: new BigNumber(value.counterValue).dividedBy(totalBalanceOnCounterAsset).multipliedBy(100).toNumber()
};
})));
Example #9
Source File: token-price.service.ts From gnosis.1inch.exchange with MIT License | 6 votes |
public getUsdTokenPrice(
tokenAddress: string,
tokenDecimals: number,
blockNumber?: number | 'latest',
): Observable<BigNumber> {
if (this.usdPriceCache$[tokenAddress]) {
return this.usdPriceCache$[tokenAddress];
}
const tokenPrice$ = this.getTokenPriceBN(
tokenAddress,
tokenDecimals,
blockNumber,
);
this.usdPriceCache$[tokenAddress] = new RefreshingReplaySubject<BigNumber>(
() => tokenPrice$,
10000
);
return this.usdPriceCache$[tokenAddress];
}
Example #10
Source File: wallet-dashboard.component.ts From xBull-Wallet with GNU Affero General Public License v3.0 | 6 votes |
lpAssetsBalances$: Observable<BalanceLineLiquidityPool[]> = this.selectedAccount$
.pipe(map(selectedAccount => {
if (!selectedAccount || !selectedAccount.accountRecord) {
return [];
}
return selectedAccount.accountRecord
.balances
.filter(b => b.asset_type === 'liquidity_pool_shares') as BalanceLineLiquidityPool[];
}));
Example #11
Source File: websocket-client.ts From closer-sdk.js with MIT License | 6 votes |
/**
* Cold observable
* @param command Message
*/
public ask(command: roomCommand.SendMessage | roomCommand.SendCustomMessage): Observable<chatEvents.Received> {
const ref = this.uuidGenerator.next();
const newCommand = { ...command, ref };
return merge(
of(newCommand).pipe(
tap((cmd: typeof newCommand) => this.send(cmd)),
ignoreElements(),
),
this.connection$.pipe(
filter(chatEvents.Received.isReceived),
filter(rec => rec.ref === ref),
),
this.connection$.pipe(
filter(errorEvents.Error.isError),
filter(rec => rec.ref === ref),
mergeMap(err => throwError(err, undefined)),
),
).pipe(
timeout(this.askTimeoutMs),
take(1),
);
}
Example #12
Source File: wallet-dashboard.component.ts From xBull-Wallet with GNU Affero General Public License v3.0 | 6 votes |
lockedXLMs$: Observable<string> = this.accountBalancesRegularAssets$
.pipe(withLatestFrom(this.selectedAccount$))
.pipe(map(([balances, selectedAccount]) => {
const nativeValue: BalanceLineNative = balances.find(b => b.asset_type === 'native') as BalanceLineNative;
if (!selectedAccount.accountRecord) {
return '0';
}
return new BigNumber(nativeValue.balance)
.minus(
this.stellarSdkService.calculateAvailableBalance({
account: selectedAccount.accountRecord,
balanceLine: nativeValue
})
)
.toFixed(7);
}));
Example #13
Source File: web3.service.ts From gnosis.1inch.exchange with MIT License | 6 votes |
public getInstance(abi: any[], address: string): Observable<Contract> {
return this.web3$.pipe(
map((web3) => {
// @ts-ignore
return (new web3.eth.Contract(
abi,
address
)) as Contract;
}),
);
}
Example #14
Source File: wallet-dashboard.component.ts From xBull-Wallet with GNU Affero General Public License v3.0 | 6 votes |
assetsBalancesWithCounterValues$: Observable<Array<{
asset?: IWalletAssetModel;
counterValue: BigNumber
}>> = this.accountBalancesRegularAssets$
.pipe(switchMap(accountBalanceLines => {
const objectMap = new Map();
for (const accountBalanceLine of accountBalanceLines) {
objectMap.set(this.walletsAssetsService.formatBalanceLineId(accountBalanceLine), accountBalanceLine);
}
return this.walletsAssetsQuery.selectAll({
filterBy: entity => !!objectMap.get(entity._id)
})
.pipe(debounceTime(100))
.pipe(map(assets => {
return assets.map(asset => ({
asset,
counterValue: !asset || !asset.counterPrice
? new BigNumber(0)
: new BigNumber(asset.counterPrice)
.multipliedBy(objectMap.get(asset._id).balance)
}))
.filter(data => !!data.asset);
}));
}));
Example #15
Source File: logging.interceptor.ts From 42_checkIn with GNU General Public License v3.0 | 6 votes |
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const now = Date.now();
return next
.handle()
.pipe(
tap(() =>
this.logger.log(
context.switchToHttp().getRequest().route.path,
context.getHandler().name,
Date.now() - now + 'ms',
),
),
);
}
Example #16
Source File: gcloud-storage-files.interceptor.ts From nestjs-gcloud-storage with MIT License | 6 votes |
export function GCloudStorageFilesInterceptor(
fieldName: string,
localOptions?: MulterOptions,
gcloudStorageOptions?: Partial<GCloudStoragePerRequestOptions>,
): Type<NestInterceptor> {
@Injectable()
class MixinInterceptor implements NestInterceptor {
public interceptor: NestInterceptor;
constructor(private readonly gcloudStorage: GCloudStorageService) {
this.interceptor = new (FilesInterceptor(fieldName, 20, localOptions))();
}
async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
(await this.interceptor.intercept(context, next)) as Observable<any>;
const request = context.switchToHttp().getRequest();
const files = request[fieldName];
if (!files.length) {
Logger.error(
'GCloudStorageFilesInterceptor',
`Can not intercept field "${fieldName}". Did you specify the correct field name in @GCloudStorageFilesInterceptor('${fieldName}')?`,
);
return;
}
for (const file of files) file.storageUrl = await this.gcloudStorage.upload(file, gcloudStorageOptions);
return next.handle();
}
}
const Interceptor = mixin(MixinInterceptor);
return Interceptor as Type<NestInterceptor>;
}
Example #17
Source File: settings.service.ts From xBull-Wallet with GNU Affero General Public License v3.0 | 6 votes |
getRecommendedFee(): Observable<string> {
this.settingsStore.updateUIState({ gettingRecommendedFee: true });
return this.stellarSdkService.getRecommendedFee()
.pipe(tap(() => this.settingsStore.updateUIState({ gettingRecommendedFee: false })))
.pipe(catchError(error => {
this.settingsStore.updateUIState({ gettingRecommendedFee: false });
return throwError(error);
}));
}
Example #18
Source File: unauthorized.interceptor.ts From Smersh with MIT License | 6 votes |
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error && [401, 403].includes(error.status)) {
this.router.navigateByUrl(DashboardRouter.redirectToList());
}
return throwError(error);
})
);
}
Example #19
Source File: spawn-process.ts From nx-plugins with MIT License | 6 votes |
export function spawnProcess(
command: string,
args: string[] = [],
{ silent, env = process.env, ...options }: ProcessOptions = {},
): Observable<ProcessOutput> {
return new Observable<ProcessOutput>((observer) => {
const child = spawn(command, args, { ...options, env: processEnv(env) });
if (!silent) {
console.log(`${command} ${args.join(' ')}`);
}
const processExitListener = () => {
observer.complete();
child.kill();
};
process.on('exit', processExitListener);
if (!('stdio' in options)) {
child.stdout.on('data', (data) => {
observer.next({ type: 'OUT', data });
});
child.stderr.on('data', (data) => {
observer.next({ type: 'ERR', data });
});
}
child.on('close', (code) => {
if (code === 0) {
observer.complete();
} else {
observer.error();
}
process.removeListener('exit', processExitListener);
});
});
}
Example #20
Source File: wallet-account.component.ts From xBull-Wallet with GNU Affero General Public License v3.0 | 6 votes |
account$: Observable<IWalletsAccount> = combineLatest([
this.publicKey,
this.horizonApisQuery.getSelectedHorizonApi$
])
.pipe(switchMap(([publicKey, horizonApi]) => {
const accountId = this.walletsService.generateWalletAccountId({
publicKey,
network: horizonApi.networkPassphrase as Networks,
});
return this.walletsAccountsQuery.selectEntity(accountId) as Observable<IWalletsAccount>;
}));
Example #21
Source File: process-output.ts From nx-plugins with MIT License | 6 votes |
export function log() {
return (source: Observable<ProcessOutput>): Observable<ProcessOutput> =>
source.pipe(
tap(({ type, data }) => {
if (type === 'OUT') {
process.stdout.write(data.toString());
} else {
process.stderr.write(data.toString());
}
}),
);
}
Example #22
Source File: claimable-balances-dashboard.component.ts From xBull-Wallet with GNU Affero General Public License v3.0 | 6 votes |
listItems$: Observable<IClaimableBalanceLineItem[]> = this.filteredClaimableBalances$
.pipe(switchMap((filteredClaimableBalances) => {
return this.walletsAssetsQuery.selectAll({
filterBy: entity => {
return !!filteredClaimableBalances
.find(c => entity._id === this.walletsAssetsService.assetIdFromAssetString(c.asset));
}
})
.pipe(distinctUntilChanged((a, b) => JSON.stringify(a) !== JSON.stringify(b)))
.pipe(map(assets => {
const items = [];
for (const asset of assets) {
const claimableBalance = filteredClaimableBalances
.find(c => this.walletsAssetsService.assetIdFromAssetString(c.asset) === asset._id);
if (!!claimableBalance) {
items.push({
_id: claimableBalance.id,
image: asset.image,
assetCode: asset.assetCode,
amount: claimableBalance.amount,
assetIssuer: asset.assetIssuer,
domain: asset.domain,
});
}
}
return items;
}));
}));
Example #23
Source File: GridEngine.ts From grid-engine with Apache License 2.0 | 6 votes |
/**
* @returns Observable that emits when a new character is added or an existing is removed.
*/
characterShifted(): Observable<CharacterShift> {
return this.charAdded$.pipe(
map((c) => ({
charId: c,
action: CharacterShiftAction.ADDED,
})),
mergeWith(
this.charRemoved$.pipe(
map((c) => ({
charId: c,
action: CharacterShiftAction.REMOVED,
}))
)
)
);
}
Example #24
Source File: operations-dashboard.component.ts From xBull-Wallet with GNU Affero General Public License v3.0 | 6 votes |
accountOperations$: Observable<IWalletsOperation[]> = this.selectedAccount$
.pipe(filter(account => !!account))
.pipe(distinctUntilKeyChanged('_id'))
.pipe(withLatestFrom(this.settingsQuery.antiSpamPublicKeys$))
.pipe(switchMap(([account, antiSpamPublicKeys]) => {
return this.walletsOperationsQuery.selectAll({
filterBy: entity => entity.ownerAccount === account._id
&& !antiSpamPublicKeys.find(key => entity.operationRecord.source_account === key),
sortBy: (entityA, entityB) => entityB.createdAt - entityA.createdAt,
});
}))
.pipe(debounceTime(10));
Example #25
Source File: GridEngine.d.ts From grid-engine with Apache License 2.0 | 6 votes |
/**
* Initiates movement toward the specified `targetPos`. The movement will
* happen along one shortest path. Check out {@link MoveToConfig} for
* pathfinding configurations.
*
* @returns an observable that will fire
* whenever the moveTo movement is finished or aborted. It will provide a
* {@link MoveToResult | result code} as well as a description and a character
* layer.
*/
moveTo(charId: string, targetPos: Position, config?: MoveToConfig): Observable<{
charId: string;
} & Finished>;
Example #26
Source File: withdraw-liquidity.component.ts From xBull-Wallet with GNU Affero General Public License v3.0 | 6 votes |
accountBalances$: Observable<BalanceLine<'liquidity_pool_shares'>[]> = this.selectedAccount$
.pipe(filter<any>(Boolean))
.pipe(map((selectedAccount: IWalletsAccount) => {
return selectedAccount.accountRecord
? selectedAccount.accountRecord.balances
.filter(b =>
b.asset_type === 'liquidity_pool_shares'
&& new BigNumber(b.balance).isGreaterThan(0)
) as BalanceLine<'liquidity_pool_shares'>[]
: [];
}));
Example #27
Source File: GridEngine.ts From grid-engine with Apache License 2.0 | 6 votes |
/**
* @returns Observable that, whenever a specified position is entered on optionally provided layers,
* will notify with the target characters position change
*/
steppedOn(
charIds: string[],
tiles: Position[],
layer?: string[]
): Observable<
{
charId: string;
} & PositionChange
> {
return this.positionChangeFinished().pipe(
filter(
(t) =>
charIds.includes(t.charId) &&
tiles.some(
(target) => target.x === t.enterTile.x && target.y === t.enterTile.y
) &&
(layer === undefined || layer.includes(t.enterLayer))
)
);
}
Example #28
Source File: lp-asset-details.component.ts From xBull-Wallet with GNU Affero General Public License v3.0 | 6 votes |
reserves$: Observable<Array<IWalletAsset<any, 'full'>>> = this.lpAsset$
.pipe(filter<any>(lpAsset => !!lpAsset?.dataLoaded))
.pipe(switchMap((lpAsset: ILpAssetLoaded) => {
const [assetACode, assetBCode] = lpAsset.reserves.map(reserve => {
return reserve.asset.includes(':')
? reserve.asset.split(':')[0] + '_' + reserve.asset.split(':')[1]
: 'native';
});
return combineLatest([
this.walletsAssetsQuery.selectEntity(assetACode),
this.walletsAssetsQuery.selectEntity(assetBCode),
]);
})) as Observable<Array<IWalletAsset<any, 'full'>>>;
Example #29
Source File: GridEngine.d.ts From grid-engine with Apache License 2.0 | 6 votes |
/**
* @returns Observable that will notify about every change of direction that
* is not part of a movement. This is the case if the character tries to walk
* towards a blocked tile. The character will turn but not move.
*/
directionChanged(): Observable<{
charId: string;
direction: Direction;
}>;