rxjs#from JavaScript Examples
The following examples show how to use
rxjs#from.
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: staking_payouts.js From sdk with MIT License | 6 votes |
getUnclaimedStashesEras = curry((api, { eras }, stashIds$) =>
// Concurrently get unclaimed eras for each of stashes
stashIds$.pipe(
mergeMap(
(stashId) =>
from(getUnclaimedStashEras(api, eras, stashId)).pipe(
// Filter out stashes with no unclaimed eras
filterRx(complement(isEmpty)),
mapRx(assoc("eras", __, { stashId }))
),
ConcurrentRequestsLimit
)
)
)
Example #2
Source File: staking_payouts.js From sdk with MIT License | 6 votes |
signAndSendExtrinsics = curry((dock, initiator, txs$) => {
// The first nonce to be used will come from the API call
// To send several extrinsics simultaneously, we need to emulate increasing nonce
return from(dock.api.rpc.system.accountNextIndex(initiator.address)).pipe(
switchMap((nonce) => {
const sendExtrinsic = (tx) =>
defer(() => {
dock.setAccount(initiator);
const sentTx = dock.signAndSend(tx, FinalizeTx, { nonce });
// Increase nonce by hand
nonce = nonce.add(new BN(1));
return from(timeout(TxFinalizationTimeout, sentTx));
}).pipe(
mapRx((result) => ({ tx, result })),
catchError((error, caught) => {
console.error(` * Transaction failed: ${error}`);
const stringified = error.toString().toLowerCase();
// Filter out errors related to balance and double-claim
if (
stringified.includes("balance") ||
stringified.includes("alreadyclaimed") ||
stringified.includes("invalid transaction") ||
stringified.includes("election")
) {
return EMPTY;
} else {
// Retry an observable after the given timeout
return timer(RetryTimeout).pipe(concatMapTo(caught));
}
})
);
return txs$.pipe(mergeMap(sendExtrinsic, ConcurrentTxLimit));
})
);
})
Example #3
Source File: OnlineAccountClient.js From invizi with GNU General Public License v3.0 | 6 votes |
// Fetch all trades, all deposits and withdraws
// returns obs
synchronizeTransactions (account, symbolCurrencyPair, apiKeys, params) {
const allTrades$ = this.getMyTradesObs(...arguments)
const withdrawals$ = this.getWithdrawalsObs(...arguments)
const deposits$ = from(this.getDepositsObs(...arguments))
const timer$ = timer(5000)
const maxIter = this.allTransactionsMaxIter(account.name)
let currentIter = 1
let load$ = concat(deposits$, timer$, withdrawals$, timer$, allTrades$).pipe(
tap(data => {
console.log(data)
}),
filter(data => data), // filter timerObs values
map(result => {
let tradesFiltered = result.data
// if (account.last_sync_at) {
// tradesFiltered = result.data.filter(trade => trade.date > account.last_sync_at / 1000)
// }
tradesFiltered.progress = (currentIter + 1) / maxIter
currentIter++
return result
})
)
return load$
}
Example #4
Source File: index.js From discovery-mobile-ui with MIT License | 6 votes |
initializeFhirClient = (action$, state$, { fhirClient }) => action$.pipe(
ofType(actionTypes.SET_AUTH),
// delay(5000), // e.g.: for debugging -- import delay from rxjs/operators
concatMap(({ payload }) => {
if (payload === MOCK_AUTH) {
return Promise.resolve({
type: actionTypes.FHIR_FETCH_SUCCESS,
payload: MOCK_BUNDLE,
});
}
return from(fhirClient.queryPatient())
.pipe(
mergeMap((requestFn) => from(requestFn()).pipe(
rxMap((result) => ({
type: actionTypes.FHIR_FETCH_SUCCESS,
payload: result,
})),
catchError((error) => handleError(error, 'Error in queryPatient', actionTypes.FHIR_FETCH_ERROR)),
)),
);
}),
takeUntil(action$.pipe(ofType(actionTypes.CLEAR_PATIENT_DATA))),
repeat(),
catchError((error) => handleError(error, 'Error in initializeFhirClient switchMap')),
)
Example #5
Source File: index.js From discovery-mobile-ui with MIT License | 6 votes |
requestNextItems = (action$, state$, { fhirClient }) => action$.pipe(
ofType(actionTypes.FHIR_FETCH_SUCCESS),
// delay(1000), // e.g.: for debugging
concatMap(({ payload }) => from(extractNextUrls(payload)).pipe(
concatMap((url) => fhirClient.request(url)),
).pipe(
rxMap((result) => ({
type: actionTypes.FHIR_FETCH_SUCCESS,
payload: result,
})),
catchError((error) => handleError(error, 'Error in requestNextItems nextRequests$.pipe')),
)),
takeUntil(action$.pipe(ofType(actionTypes.CLEAR_PATIENT_DATA))),
repeat(),
catchError((error) => handleError(error, 'Error in requestNextItems concatMap')),
)
Example #6
Source File: index.js From discovery-mobile-ui with MIT License | 6 votes |
resolveReferences = (action$, state$, { fhirClient }) => action$.pipe(
ofType(actionTypes.RESOURCE_BATCH),
// delay(1000), // e.g.: for debugging
concatMap(({ payload }) => from(extractReferences(payload))
.pipe(
mergeMap(({
referenceUrn, context, // referenceType, parentType,
}) => from(fhirClient.resolve({ reference: referenceUrn, context })).pipe(
// tap(() => console.log('Silent success referenceUrn', referenceUrn)),
rxMap((result) => ({
type: actionTypes.FHIR_FETCH_SUCCESS,
payload: result,
})),
catchError((error) => handleError(error, `Error in resolveReferences fhirClient.resolve urn:\n ${referenceUrn}`)),
)),
)),
takeUntil(action$.pipe(ofType(actionTypes.CLEAR_PATIENT_DATA))),
repeat(),
catchError((error) => handleError(error, 'Error in resolveReferences')),
)
Example #7
Source File: staking_payouts.js From sdk with MIT License | 4 votes |
/**
* Sends staking payouts for recent eras using the given sender account.
*
* @param {DockAPI} dock
* @param {ErasInfo} erasInfo
* @param {*} initiator - account to send tx from
* @param {number} batchSize
* @returns {Promise<boolean>} - `true` if some unpaid eras were found, `false` otherwise
*/
async function sendStakingPayouts(dock, erasInfo, initiator, batchSize) {
const validators = pipe(
values,
pluck("validators"),
chain(keys),
(values) => new Set(values)
)(erasInfo.pointsByEra);
if (!validators.size) {
console.log("- Validator set is empty.");
return false;
}
console.log("- Retrieving validator eras...");
const erasToBePaid = await lastValueFrom(
from(validators).pipe(
getUnclaimedStashesEras(dock.api, erasInfo),
toArray()
)
);
const rewards = pipe(buildValidatorRewards, toPairs)(erasInfo, erasToBePaid);
if (isEmpty(rewards)) {
console.log("- No unpaid validator rewards found for recent eras.");
return false;
}
console.log("- Payouts need to be made:");
for (const [stashId, eras] of rewards) {
const total = eras.reduce(
(total, { reward }) => (total != null ? total.add(reward) : reward),
null
);
console.log(` * To \`${stashId}\`: ${formatDock(total)}`);
}
const logResult = ({ result, tx }) => {
// Ther's a much better way to check this...
const isBatch = tx.method.args?.[0]?.[0] instanceof Map;
let msg = " * ";
if (isBatch) msg += `Batch transaction`;
else msg += `Transaction`;
if (FinalizeTx) {
msg += ` finalized at block \`${result.status.asFinalized}\`: `;
} else {
msg += ` included at block \`${result.status.asInBlock}\`: `;
}
const payoutsSummary = (isBatch ? tx.method.args[0] : [tx.method])
.map((payout) => payout.get("args"))
.map(
({ validator_stash, era }) =>
`\`${validator_stash}\` rewarded for era ${era}`
)
.join(isBatch ? ",\n " : ",");
msg += isBatch ? `[\n ${payoutsSummary}\n ]` : payoutsSummary;
console.log(msg);
};
const payoutTxs$ = from(rewards).pipe(
concatMap(([stashId, eras]) => from(eras.map(assoc("stashId", stashId)))),
mapRx(({ stashId, era }) =>
dock.api.tx.staking.payoutStakers(stashId, era)
),
batchExtrinsics(dock.api, batchSize),
signAndSendExtrinsics(dock, initiator),
tap(logResult)
);
await new Promise((resolve, reject) =>
payoutTxs$.subscribe({
error: reject,
complete: resolve,
})
);
return true;
}