rxjs#timer TypeScript Examples
The following examples show how to use
rxjs#timer.
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: phone-verification.page.ts From capture-lite with GNU General Public License v3.0 | 6 votes |
onVerificationCodeFormSubmit() {
const CLOSE_DELAY = 3000;
const countdown$ = timer(CLOSE_DELAY).pipe(
first(),
finalize(() =>
this.router.navigate(['..'], {
relativeTo: this.route,
})
)
);
const action$ = this.diaBackendAuthService
.verifyPhoneVerification$(
this.phoneNumberModel.phoneNumber,
this.verificationCodeModel.verificationCode
)
.pipe(catchError((err: unknown) => this.handleVerificationError$(err)));
return this.blockingActionService
.run$(action$, {
message: this.translocoService.translate('message.pleaseWait'),
})
.pipe(
tap(() =>
this.snackBar.open(
this.translocoService.translate('message.verificationSuccess')
)
),
switchMap(() => countdown$),
untilDestroyed(this)
)
.subscribe();
}
Example #2
Source File: auth.service.ts From bitcoin-s-ts with MIT License | 6 votes |
private setLoginTimer(expiresIn: number) {
let time = expiresIn - LOGOUT_DELAY
console.debug('setLoginTimer()', time, 'ms')
if (time <= 0) this.showLogoutDialog(Math.floor(expiresIn / 1000))
else {
if (this.loginTime$) this.loginTime$.unsubscribe()
this.loginTime$ = timer(time).pipe(take(1)).subscribe(_ => {
this.showLogoutDialog(LOGOUT_DELAY / 1000)
})
}
}
Example #3
Source File: subscribe-to-one-raw-search.ts From js-client with MIT License | 6 votes |
makeSubscribeToOneRawSearch = (context: APIContext) => {
const templatePath = '/api/ws/search';
const url = buildURL(templatePath, { ...context, protocol: 'ws' });
return async (): Promise<APISubscription<RawSearchMessageReceived, RawSearchMessageSent>> => {
const socket = new WebSocket(url, context.authToken ?? undefined);
const rawSubscription = apiSubscriptionFromWebSocket<RawSearchMessageReceived, RawSearchMessageSent>(socket);
rawSubscription.send({ Subs: ['PONG', 'parse', 'search', 'attach'] });
const wsClosed$: Observable<void> = rawSubscription.sent$.pipe(
startWith(undefined),
// Even if the websocket hangs up due to an error, we want to emit, so that we can
// clean up the PONG subscription below
catchError(() => of(undefined)),
mapTo(undefined),
last(),
);
timer(1000, 5000)
.pipe(takeUntil(wsClosed$))
.subscribe(() => {
rawSubscription.send({ type: 'PONG', data: {} });
});
return rawSubscription;
};
}
Example #4
Source File: publish-list.tsx From bext with MIT License | 6 votes |
Banner: FC<{ current: number; empty?: boolean }> = ({
current,
empty,
}) => {
const nextTime = useObservableState(
useObservable(
(input$) =>
input$.pipe(
pluckFirst,
switchMap((current) =>
timer(0, 1000).pipe(
map(() => current + REFRESH_DURATION - Date.now()),
),
),
),
[current],
),
REFRESH_DURATION,
);
return (
<Separator>
{empty ? '暂无' : ''}发布历史({' '}
{nextTime > 0 ? `${Math.floor(nextTime / 1000)} 秒后刷新` : '刷新中'})
</Separator>
);
}
Example #5
Source File: app-common.service.ts From dayz-server-manager with MIT License | 6 votes |
public adjustRefreshRate(rate: number): void {
this.refreshRate$ = rate;
if (this.timer && !this.timer.closed) {
this.timer.unsubscribe();
}
if (rate && rate > 0) {
this.timer = timer(0, this.refreshRate$ * 1000)
.subscribe(() => {
this.triggerUpdate();
});
}
}
Example #6
Source File: email-verification.page.ts From capture-lite with GNU General Public License v3.0 | 6 votes |
async sendEmailVerification() {
const RESEND_COOLDOWN_TICKS = 60;
const TICK_INTERVAL = 1000;
const countdown$ = timer(0, TICK_INTERVAL).pipe(
take(RESEND_COOLDOWN_TICKS),
map(tick => RESEND_COOLDOWN_TICKS - tick - 1),
tap(cooldown => (this.secondsRemained = cooldown)),
finalize(() => (this.secondsRemained = 0))
);
const action$ = this.email$.pipe(
first(),
concatMap(email =>
this.diaBackendAuthService.resendActivationEmail$(email)
),
catchError((err: unknown) => this.errorService.toastError$(err))
);
return this.blockingActionService
.run$(action$, {
message: this.translocoService.translate('message.pleaseWait'),
})
.pipe(
tap(() => (this.hasSentEmailVerification = true)),
switchMap(() => countdown$),
untilDestroyed(this)
)
.subscribe();
}
Example #7
Source File: app.component.ts From Uber-ServeMe-System with MIT License | 6 votes |
initializeApp() {
this.platform.ready().then(() => {
Environment.setEnv({
'API_KEY_FOR_BROWSER_RELEASE': 'AIzaSyBfdfHVfFgZbqw40ZBzZZa7kMTrEOvxarg',
'API_KEY_FOR_BROWSER_DEBUG': 'AIzaSyBfdfHVfFgZbqw40ZBzZZa7kMTrEOvxarg'
});
this.statusBar.overlaysWebView(false);
this.statusBar.styleLightContent();
setTimeout(() => {
this.splashScreen.hide();
}, 300);
timer(3000).subscribe(() => this.showSplash = false)
});
}
Example #8
Source File: dia-backend-asset-uploading.service.ts From capture-lite with GNU General Public License v3.0 | 6 votes |
private uploadProof$(proof: Proof) {
const scalingDuration = 1000;
const attempBase = 2;
return this.diaBackendAssetRepository.addCapture$(proof).pipe(
first(),
catchError((err: unknown) => {
if (
err instanceof HttpErrorResponse &&
err.error.error.type === 'duplicate_asset_not_allowed'
) {
return this.diaBackendAssetRepository.fetchByProof$(proof);
}
return throwError(err);
}),
map(diaBackendAsset => {
proof.diaBackendAssetId = diaBackendAsset.id;
return proof;
}),
retryWhen(err$ =>
err$.pipe(
mergeMap((_, attempt) => {
return timer(attempBase ** attempt * scalingDuration);
})
)
)
);
}
Example #9
Source File: mockApiRx.ts From guardian with Apache License 2.0 | 6 votes |
MockApiRx = of({
...acalaRpc,
consts: {
prices: { stableCurrencyFixedPrice: 1e18 },
currencies: { getNativeCurrencyId: ACA },
cdpEngine: {
getStableCurrencyId: AUSD,
collateralCurrencyIds: COLLATERAL_CURRENCY_IDS
}
},
query: {
auctionManager: {
collateralAuctions: {
entries: () => of([[collateralAuctionsKey(0), COLLATERAL_AUCTION]])
}
},
auction: {
auctionsIndex: () => of(registry.createType('AuctionId', 1)),
auctions: () => of(AUCTION)
},
dex: {
liquidityPool: () => of(LP)
},
loans: {
positions: () => of(POSITION)
},
cdpEngine: {
debitExchangeRate: () => of(EXCHANGE_RATE)
},
acalaOracle: {
values: () => {
return merge([of(PRICE), timer(1000).pipe(mapTo(PRICE_UPDATED))]).pipe(concatAll(), share());
}
}
},
createType: (type: string, value: any) => registry.createType(type, value)
})
Example #10
Source File: app.component.ts From blog2020 with MIT License | 6 votes |
startHeartbeat(): void {
this.stopHeartbeat();
this.networkError = false;
const heartbeat$ = timer(1_000, 30_000)
.pipe(
tap(() => this.connect().next('ping')),
concatMap(_ => {
return race(
of('timeout').pipe(delay(3_000)),
this.connect().pipe(filter(m => m === 'pong'), catchError(() => of('error')))
);
})
);
this.heartbeatSubscription = heartbeat$.subscribe(msg => {
if (msg === 'pong') {
this.networkError = false;
} else {
this.networkError = true;
this.webSocketSubject?.complete();
this.webSocketSubject = null;
}
});
}
Example #11
Source File: connectivity-status.component.ts From storm with MIT License | 6 votes |
constructor() {
this.$connected = new Subject<boolean>();
this.$visible = this.$connected.pipe(
tap(_ => {
this.animate = false;
this.closing = false;
}),
switchMap(ok => {
if (!ok) {
// If not connected then make the status visible
return of(true);
}
// Otherwise, if connected
// Make the status visible, then after 2 seconds disable the visibility
return concat(
of(true),
// After two seconds begin the transition
timer(2000, 0).pipe(
switchMap(_ => {
this.animate = true;
this.closing = true;
return timer(1000, 0).pipe(
map(_ => false)
);
})
)
);
})
);
}
Example #12
Source File: authentication.service.ts From sba-angular with MIT License | 6 votes |
/**
* Initiate authentication using the ng2-ui-auth library. The authentication process will be performed
* in a browser popup window
*
* @param provider The name of the provider to use. This is the name configured in the Sinequa administration
* console
*/
authenticateWithProvider(provider: string): Observable<any> {
// AuthService.authenticate opens a popup. On some platforms (Firefox) this is asynchronous
// so we add a delay (timer(0)) so the caller can create a promise from the returned observable
// without yielding
const observable = timer(0).pipe(flatMap((value) => {
const observable1 = this.authService.authenticate(provider, true).pipe(share());
Utils.subscribe(observable1,
(response) => {
// NB response should be the return value from JOAuth/JSaml json methods
// It can be undefined eg if the popup fails to open
if (response) {
this.processedCredentials = {
kind: LEGACY_PROCESSED_CREDENTIALS_KIND,
data: {
csrfToken: response.csrfToken,
provider
}
};
}
});
return observable1;
}));
return observable;
}
Example #13
Source File: vg-media.ts From ngx-videogular with MIT License | 6 votes |
startSync() {
this.syncSubscription = timer(0, 1000).subscribe(
() => {
for (const media in this.api.medias) {
if (this.api.medias[media] !== this) {
const diff: number = this.api.medias[media].currentTime - this.currentTime;
if (diff < -0.3 || diff > 0.3) {
this.playAtferSync = (this.state === VgStates.VG_PLAYING);
this.pause();
this.api.medias[media].pause();
this.api.medias[media].currentTime = this.currentTime;
} else {
if (this.playAtferSync) {
this.play();
this.api.medias[media].play();
this.playAtferSync = false;
}
}
}
}
}
);
}
Example #14
Source File: info.component.ts From dev-manager-desktop with Apache License 2.0 | 6 votes |
private async loadDevModeInfo(): Promise<void> {
try {
const token = await this.deviceManager.devModeToken(this.device.name);
const devModeInfo = await this.devMode.checkDevMode(token);
this.devModeInfo = devModeInfo;
if (devModeInfo.errorCode == '200') {
const expireDate = moment().add(devModeInfo.errorMsg, 'h');
this.devModeRemaining = timer(0, 1000).pipe(map(() => moment.duration(expireDate.diff(moment())).format('hh:mm:ss')));
}
} catch (e) {
this.devModeInfo = null;
this.devModeRemaining = null;
}
}
Example #15
Source File: ɵclient.ts From scion-microfrontend-platform with Eclipse Public License 2.0 | 6 votes |
public markStaleAndQueueForRemoval(): void {
if (this._staleClientUnregisterTimer) {
return;
}
this._staleClientUnregisterTimer = timer(this._staleClientUnregisterDelay).subscribe(() => {
this.logStaleClientWarning();
Beans.get(ClientRegistry).unregisterClient(this);
});
this._heartbeat?.unsubscribe();
}
Example #16
Source File: settings.page.ts From mylog14 with GNU General Public License v3.0 | 6 votes |
onChangeLanguage(event: CustomEvent): void {
this.updateFromPage.next({ language: event.detail.value });
this.showSelects = false;
timer(50).
pipe(
first(),
tap(() => this.showSelects = true)
).subscribe();
}
Example #17
Source File: settings.service.ts From xBull-Wallet with GNU Affero General Public License v3.0 | 6 votes |
removeLocallySavedPasswordSubscription: Subscription = this.removeLocallySavedPasswordTrigger$.asObservable()
.pipe(filter(_ => this.settingsStore.getValue().keepPasswordActive))
.pipe(switchMap(_ => {
return timer(
new BigNumber(this.settingsStore.getValue().timeoutPasswordSaved)
.multipliedBy('60000')
.toNumber()
);
}))
.subscribe(_ => {
this.setKeptPassword(undefined);
});
Example #18
Source File: unknown-error.component.ts From rubic-app with GNU General Public License v3.0 | 6 votes |
/**
* Show copy to clipboard hint.
*/
private showHint(): void {
this.hintShown = true;
timer(1500).subscribe(() => {
this.hintShown = false;
this.cdr.markForCheck();
});
}
Example #19
Source File: animation.component.ts From mylog14 with GNU General Public License v3.0 | 6 votes |
private startCountdown(day: number) {
const idx = (day > 14) ? 15 : day + 1; // The animation array has +1 offset
this.animationPlay(idx);
if (idx !== 15) {
return timer(idx * 1000)
.pipe(
tap(() => this.animationStopOnDay(idx)),
);
}
}
Example #20
Source File: microfrontend-fixture.script.ts From scion-microfrontend-platform with Eclipse Public License 2.0 | 6 votes |
export async function testcase_6(): Promise<void> {
// Delay script execution.
await firstValueFrom(timer(500));
// Add testee div after delay.
const testeeDiv = document.body.appendChild(document.createElement('div'));
testeeDiv.innerText = 'TESTEE';
testeeDiv.classList.add('testee', 'delayed');
}
Example #21
Source File: emote.component.ts From App with MIT License | 6 votes |
interactError = new Subject<string>().pipe(
mergeMap(x => scheduled([
of(!!x ? 'ERROR: ' + x : ''),
timer(5000).pipe(
takeUntil(this.interactError),
mapTo('')
)
], asyncScheduler).pipe(mergeAll()))
) as Subject<string>;
Example #22
Source File: date-tooltip-cell.component.ts From WowUp with GNU General Public License v3.0 | 6 votes |
public agInit(params: ICellRendererParams): void {
this.params = params;
this.time$.next(this.params.value as string);
combineLatest([this._electronService.windowFocused$, timer(0, 30000)])
.pipe(takeUntil(this._destroy$))
.subscribe(([focused]) => {
if (!focused && this.relativeTime$.value.length > 0) {
return;
}
const [fmt, val] = getRelativeDateFormat(this.params.value as string);
if (!fmt) {
return this.relativeTime$.next("ERR");
}
this.relativeTime$.next(this._translateService.instant(fmt, val) as string);
});
}
Example #23
Source File: gas-price.api.service.ts From gnosis.1inch.exchange with MIT License | 6 votes |
constructor(private http: HttpClient) {
timer(0, 30000).pipe(
mergeMap(() => this.getGasPrice()),
tap((gasPrice: GasPrice) => {
const fast = formatGasPrice(gasPrice.fast);
const instant = formatGasPrice(gasPrice.instant);
const standard = formatGasPrice(gasPrice.standard);
this.gasPrice.next({
fast: ethers.utils.bigNumberify(Math.trunc(fast)),
standard: ethers.utils.bigNumberify(Math.trunc(standard)),
instant: ethers.utils.bigNumberify(Math.trunc(instant))
});
})
).subscribe();
}
Example #24
Source File: success-tx-modal.component.ts From rubic-app with GNU General Public License v3.0 | 6 votes |
constructor(
private readonly destroy$: TuiDestroyService,
@Inject(POLYMORPHEUS_CONTEXT)
private readonly context: TuiDialogContext<
boolean,
{
idPrefix: string;
type: SuccessTxModalType;
txHash: string;
blockchain: BlockchainName;
ccrProviderType: CrossChainProvider;
}
>
) {
this.idPrefix = context.data.idPrefix;
this.type = context.data.type;
this.txHash = context.data.txHash;
this.blockchain = context.data.blockchain;
this.ccrProviderType = context.data.ccrProviderType;
timer(MODAL_CONFIG.modalLifetime)
.pipe(takeUntil(this.destroy$))
.subscribe(() => this.onConfirm());
}
Example #25
Source File: artichoke.ts From closer-sdk.js with MIT License | 5 votes |
// tslint:disable-next-line: no-any
private delayReconnect(observable: Observable<any>): Observable<void> {
return observable.pipe(delayWhen(() => timer(this.getReconnectDelay())));
}
Example #26
Source File: PoolInfoTask.ts From guardian with Apache License 2.0 | 5 votes |
getPoolState = (apiRx: ApiRx, poolId: LiquidityPoolId, period: number) => {
const stream$ = timer(0, period).pipe(
switchMap(() => apiRx.rpc.margin.poolState(poolId)),
distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b)),
shareReplay({ refCount: true, bufferSize: 1 })
);
return stream$;
}
Example #27
Source File: volume-api.service.ts From rubic-app with GNU General Public License v3.0 | 5 votes |
/**
* Makes request for trade volumes with interval and updates data volume.
*/
private setTradeVolumeInterval(): void {
timer(0, 1000 * 60 * 60)
.pipe(switchMap(() => this.fetchVolume()))
.subscribe(volume => this.tradeVolume$.next(volume));
}
Example #28
Source File: app.component.ts From storm with MIT License | 5 votes |
/**
* Updates the list of torrents at every given interval,
* or when the selected $get state is updated.
* @param interval
* Update interval in milliseconds
*/
private refreshInterval(interval: number): void {
const timer$ = timer(0, interval);
// Ensure the label plugin is enabled
const labelPluginEnabled$ = this.api.plugins().pipe(
switchMap(plugins => {
const ok = plugins.findIndex(name => name === 'Label') > -1;
if (ok) {
return of(true)
}
return this.enableLabelPlugin()
})
)
const interval$ = combineLatest([timer$, this.focus.observe, this.get$, labelPluginEnabled$]);
interval$.pipe(
// Continue only when in focus
filter(([_, focus, state, pluginEnabled]) => focus),
// Switch to API response of torrents
mergeMap(([_, focus, state]) => {
const torrents$ = this.api.torrents(state).pipe(
catchError(() => {
this.connected = false;
return EMPTY;
}),
)
const labels$ = this.api.torrentsLabels(state)
return forkJoin({
torrents: torrents$,
labels: labels$,
})
}),
// Tap view information
tap(response => this.empty = !this.tapEmptyView(response.torrents)),
tap(response => this.stateInView = this.tapStateInView(response.torrents)),
tap(response => this.hashesInView = this.tapHashesInView(response.torrents)),
map(response => this.transformResponse(response)),
).subscribe(
response => {
this.torrents = response;
this.connected = true;
}
);
}
Example #29
Source File: helpers.ts From guardian with Apache License 2.0 | 5 votes |
observeRPC = <T>(method: RpcRxResult<any>, params: Parameters<any>, period: number): Observable<T> => {
return timer(0, period).pipe(
switchMap(() => {
return method(...params) as Observable<T>;
})
);
}