rxjs/operators#delay TypeScript Examples

The following examples show how to use rxjs/operators#delay. 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: 1inch.api.service.ts    From gnosis.1inch.exchange with MIT License 6 votes vote down vote up
function delayedRetry(delayMs: number, maxRetry = DEFAULT_MAX_RETRIES) {
  let retries = maxRetry;

  return (src: Observable<any>) =>
    src.pipe(
      retryWhen((errors: Observable<any>) => errors.pipe(
        delay(delayMs),
        mergeMap(error => retries-- > 0 ? of(error) : throwError(error))
      ))
    );
}
Example #2
Source File: epics.ts    From anthem with Apache License 2.0 6 votes vote down vote up
monthlySummaryEmailBannerEpic: EpicSignature = (action$, state$) => {
  return action$.pipe(
    filter(
      isActionOf([Actions.setAddressSuccess, Actions.initializeAppSuccess]),
    ),
    filter(() => {
      // Make development easier, whatever...
      if (ENV.ENABLE_MOCK_APIS) {
        return true;
      }

      const dismissed = state$.value.app.app.dismissedBannerKeys;
      return !dismissed.has("monthly_summary_newsletter");
    }),
    take(1),
    delay(2500),
    map(() =>
      Actions.toggleNotificationsBanner({
        key: "monthly_summary_newsletter",
        visible: true,
      }),
    ),
  );
}
Example #3
Source File: background.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
portResponseSubscription: Subscription = merge(
    this.connectHandler$,
    this.signXDRHandler$
  )
    .pipe(catchError(error => {
      console.error(error);
      return of({
        error: true,
        errorMessage: 'Connection failed',
      });
    }))
    .pipe(delay(800))
    .pipe(withLatestFrom(this.connectedPort$))
    .pipe(takeUntil(this.componentDestroyed$))
    .subscribe(([response, port]) => {
      port.postMessage(response);
      port.disconnect();
      window.close();
    });
Example #4
Source File: instant-trades-api.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Sends request to add trade.
   * @return InstantTradesResponseApi Instant trade object.
   */
  public createTrade(
    hash: string,
    provider: INSTANT_TRADE_PROVIDER,
    trade: InstantTrade,
    fee?: number,
    promoCode?: string
  ): Observable<InstantTradesResponseApi> {
    const hashObject = InstantTradesApiService.getHashObject(trade.blockchain, hash);
    const tradeInfo: InstantTradesPostApi = {
      network: TO_BACKEND_BLOCKCHAINS[trade.blockchain],
      provider,
      from_token: trade.from.token.address,
      to_token: trade.to.token.address,
      from_amount: Web3Pure.toWei(trade.from.amount, trade.from.token.decimals),
      to_amount: Web3Pure.toWei(trade.to.amount, trade.to.token.decimals),
      user: this.authService.userAddress,
      fee,
      promocode: promoCode,
      ...hashObject
    };

    const url = instantTradesApiRoutes.createData(this.walletConnectorService.provider.walletType);
    return this.httpService.post<InstantTradesResponseApi>(url, tradeInfo).pipe(delay(1000));
  }
Example #5
Source File: basic-form.component.ts    From ng-devui-admin with MIT License 6 votes vote down vote up
validateDate(value: any): Observable<any | null> {
    let message = null;
    for (const item of value) {
      if (item.id === '2') {
        message = {
          'zh-cn': `当前日期队列已满`,
          'en-us': 'The task queue on the current execution day (Tuesday) is full.',
        };
      }
    }
    // Returned by the simulated backend interface
    return of(message).pipe(delay(300));
  }
Example #6
Source File: popover.service.ts    From mylog14 with GNU General Public License v3.0 6 votes vote down vote up
private presentPopover(popover: HTMLIonPopoverElement, dismissTime?: number): Observable<any> {
    const manualDismiss$ = defer(() => popover.present())
      .pipe(
        switchMap(() => from(popover.onDidDismiss())),
      );
    const autoDismiss$ = defer(() => popover.present())
      .pipe(
        delay(dismissTime),
        switchMap(() => popover.dismiss()),
      );
    return (dismissTime) ? autoDismiss$ : manualDismiss$;
  }
Example #7
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 #8
Source File: heroes.sagas.ts    From nestjs-geteventstore with MIT License 6 votes vote down vote up
@Saga()
  dragonKilled = (events$: Observable<any>): Observable<ICommand> => {
    return events$.pipe(
      //@ts-ignore
      filter((ev) => ev instanceof HeroKilledDragonEvent),
      //@ts-ignore
      delay(400),
      //@ts-ignore
      map((event: HeroKilledDragonEvent) => {
        this.context.setCachedValue(
          CONTEXT_CORRELATION_ID,
          event?.metadata?.correlation_id || v4(),
        );
        console.log(
          clc.redBright('Inside [HeroesGameSagas] Saga after a little sleep'),
        );
        console.log(event);
        return new DropAncientItemCommand(event.data.heroId, itemId);
      }),
    );
  };
Example #9
Source File: emote-card.component.ts    From App with MIT License 6 votes vote down vote up
/**
	 * On Right Click: open quick actions menu
	 */
	@HostListener('contextmenu', ['$event'])
	onRightClick(ev: MouseEvent): void {
		ev.preventDefault(); // Stop the default context menu from opening

		if (!!this.emote) this.openContext.next(this.emote);
		this.contextMenuTrigger?.openMenu();

		this.contextMenuTrigger?.menuClosed.pipe(
			take(1),
			delay(50),
			tap(() => this.updateBorderColor())
		).subscribe();
	}
Example #10
Source File: install-from-protocol-dialog.component.ts    From WowUp with GNU General Public License v3.0 6 votes vote down vote up
public ngAfterViewInit(): void {
    of(true)
      .pipe(
        first(),
        delay(1000),
        switchMap(() => from(this.loadAddon())),
        catchError((e) => {
          console.error(e);
          return of(undefined);
        })
      )
      .subscribe();
  }
Example #11
Source File: orders-chart.component.ts    From ngx-admin-dotnet-starter with MIT License 6 votes vote down vote up
ngAfterViewInit(): void {
    this.theme.getJsTheme()
      .pipe(
        takeWhile(() => this.alive),
        delay(1),
      )
      .subscribe(config => {
        const eTheme: any = config.variables.orders;

        this.setOptions(eTheme);
        this.updateOrdersChartOptions(this.ordersChartData);
      });
  }
Example #12
Source File: basic-info-form.component.ts    From careydevelopmentcrm with MIT License 6 votes vote down vote up
private checkEmail(control: AbstractControl): Observable<ValidationErrors | null> {
    if (control.value && (<string>control.value).trim().length > 0) {
      return of(control.value).pipe(
        delay(500),
        switchMap((email) => this.contactService.doesEmailExist(email).pipe(
          map(emailExists => emailExists ? { emailExists: true } : null)
        ))
      );
    } else {
      return of(null);
    }
  }
Example #13
Source File: app.component.ts    From json-schema-form with Apache License 2.0 6 votes vote down vote up
/**
   * called whenever the user types something
   */
  filter(value: any, schema: Schema, current: string, choices: Observable<Choice[]>): Observable<Choice[]> {
    // filter and convert to Choice[]
    const filtered = this.countries.filter(c => current ? ('' + c).toLowerCase().includes(('' + current).toLowerCase()) : true);

    // limit to 5 preview results
    while (filtered.length > 5) {
      filtered.pop();
    }

    const mapped: Choice[] = filtered.map(c => ({ name: c, value: c }));

    // return with a delay of 0.5 second to simulate an HTTP call
    console.log('requesting data for ' + current);
    return of(mapped).pipe(delay(500));
  }
Example #14
Source File: text-input-preview.component.ts    From halstack-angular with Apache License 2.0 6 votes vote down vote up
callbackFunc(newValue) {
    console.log(newValue);
    const newOptions = this.options.filter((option) => {
      console.log(option);
      return option.toUpperCase().includes(newValue.toUpperCase());
    });
    return of(newOptions).pipe(
      switchMap((options) => of(options).pipe(delay(1000)))
    );
  }
Example #15
Source File: network.service.ts    From fyle-mobile-app with MIT License 6 votes vote down vote up
getConnectionStatus() {
    return this.isConnected$.pipe(
      startWith(true),
      pairwise(),
      switchMap(([previousConnectionStatus, currentConnectionStatus]) => {
        if (previousConnectionStatus === false && currentConnectionStatus === true) {
          return concat(
            of(ConnectionMessageStatus.onlineMessageShown),
            of(ConnectionMessageStatus.onlineMessageHidden).pipe(delay(3000))
          );
        } else if (previousConnectionStatus === true && currentConnectionStatus === true) {
          return of(ConnectionMessageStatus.onlineMessageHidden);
        } else {
          return of(ConnectionMessageStatus.disconnected);
        }
      })
    );
  }
Example #16
Source File: attach-search.ts    From js-client with MIT License 6 votes vote down vote up
attachSearch = (
	rawSubscription: APISubscription<RawSearchMessageReceived, RawSearchMessageSent>,
	searchID: NumericID,
): Promise<RawSearchAttachedMessageReceived> => {
	// Generate a unique ID for the search initiating request
	const requestID = uuidv4();

	// Create a promise to receive search initation results
	const results$ = SEARCH_ATTACH_RESULTS.pipe(
		// We only want results relevant to this request
		filter(({ requestID: msgRequestID }) => msgRequestID === requestID),

		// There's only one response to the request, so we're done after the first
		first(),

		// If msg.data.Error is nil, the backend is happy  - continue
		// If msg.data.Error is NON-nil, there's a problem - reject
		concatMap(({ msg }) => (isNil(msg.data.Error) ? of(msg) : throwError(msg))),

		// It takes the backend a fraction of a second to be ready for requests after we set up the search
		delay(200),
	);

	// set up the promise so we can subscribe then next the queue
	const resultsP = firstValueFrom(results$);

	// Now that we're ready to receive results (with resultsP), we can push on the queue to kick off the search initiation process
	ATTACH_QUEUE.next({ requestID, rawSubscription, searchID });

	return resultsP;
}
Example #17
Source File: tour.service.ts    From ngx-ui-tour with MIT License 6 votes vote down vote up
private showStep(step: T): void {
        const anchor = this.anchors[step && step.anchorId];

        if (!anchor) {
            if (step.isAsync) {
                this.anchorRegister$
                    .pipe(
                        filter(anchorId => anchorId === step.anchorId),
                        first(),
                        delay(0)
                    )
                    .subscribe(
                        () => this.showStep(step)
                    );
                return;
            }
            if (step.isOptional) {
                this.direction === Direction.Forwards ? this.next() : this.prev();
                return;
            }

            console.warn(
                'Can\'t attach to unregistered anchor with id ' + step.anchorId
            );
            this.end();
            return;
        }
        anchor.showTourStep(step);
        this.stepShow$.next(step);
    }
Example #18
Source File: auth.service.ts    From mns with MIT License 6 votes vote down vote up
checkLogin(username, password): Observable<boolean | void> {
    // logic to check password

    return this.userService.findUser(username, password).pipe(
      map(userFromBackend => {
        if (userFromBackend && userFromBackend.token) {

          // Get user data from Browser!!
          localStorage.setItem('currentUserKey', JSON.stringify(userFromBackend.token));

          console.log('User Found !!--- ');

          return true;
        }
        return false;

      }),
      delay(500)); // Delay just for fun !!!
  }
Example #19
Source File: audit.service.ts    From dayz-server-manager with MIT License 6 votes vote down vote up
public constructor(
        protected pipe: DecimalPipe,
        protected appCommon: AppCommonService,
    ) {

        this.listenToPlayerChanges();

        this._search$
            .pipe(
                tap(() => this._loading$.next(true)),
                debounceTime(120),
                switchMap(() => this._search()),
                delay(120),
                tap(() => this._loading$.next(false)),
            )
            .subscribe((result) => {
                this._audits$.next(result.audits);
                this._total$.next(result.total);
            });

        this._search$.next();
    }
Example #20
Source File: form.component.ts    From open-source with MIT License 6 votes vote down vote up
// notify the dynControls about the incoming data
  patchValue(value: any): void {
    this.whenReady().pipe(
      tap(() => {
        this.node.markAsPending();
        this.logger.formCycle('PrePatch');
        this.callHook('PrePatch', value);
      }),
      delay(20), // waits any PrePatch loading change
      switchMap(() => {
        this.node.markAsLoaded();
        return this.whenReady();
      }),
      tap(() => {
        this.logger.formCycle('PostPatch', this.form.value);
        this.form.patchValue(value);
        this.callHook('PostPatch', value);
      }),
    ).subscribe();
  }
Example #21
Source File: orders-chart.component.ts    From digital-bank-ui with Mozilla Public License 2.0 6 votes vote down vote up
ngAfterViewInit(): void {
    this.theme.getJsTheme()
      .pipe(
        takeWhile(() => this.alive),
        delay(1),
      )
      .subscribe(config => {
        const eTheme: any = config.variables.orders;

        this.setOptions(eTheme);
        this.updateOrdersChartOptions(this.ordersChartData);
      });
  }
Example #22
Source File: trade-logs.effects.ts    From zorro-fire-log with MIT License 6 votes vote down vote up
onTradeLogUpdate$ = createEffect(() =>
    iif(
      () => this.useMockData,
      of(
        addTradeLogs({
          tradeLogs: mockTradeLogs,
        })
      ).pipe(
        delay(500),
        tap(() => console.warn('Using MOCKED data'))
      ),
      this.store.select(selectLatestEntryTime).pipe(
        map(
          (latest) =>
            latest && new Timestamp(latest.seconds, latest.nanoseconds).toDate()
        ),
        take(1),
        switchMap((latest) =>
          merge(
            ...environment.tradeLogs.map((tl) =>
              this.firestore
                .collection<TradeLogEntry>(tl, (ref) =>
                  (latest ? ref.where('close', '>', latest) : ref).orderBy(
                    'close'
                  )
                )
                .valueChanges({ idField: 'id' })
                .pipe(
                  map((entries) => entries.map((e) => ({ ...e, alias: tl })))
                )
            )
          ).pipe(
            tap(() => console.warn('Using LIVE data')),
            map((tradeLogs) => addTradeLogs({ tradeLogs }))
          )
        )
      )
    )
  );
Example #23
Source File: app.component.ts    From blog2020 with MIT License 6 votes vote down vote up
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 #24
Source File: torrent-edit-label-dialog.component.ts    From storm with MIT License 6 votes vote down vote up
onApplySuggestion(suggestion: LabelSuggestion): void {
    // Do nothing if the label is unchanged
    if (suggestion.value === this.initialLabel && !suggestion.new) {
      this.ref.close();
      return;
    }

    let prep$: Observable<void> = of(null)

    // If the label is not empty then check it is not one of the existing labels
    if (suggestion.value && suggestion.new) {
      prep$ = this.api.createLabel(suggestion.value).pipe(
        // Deluge has issues when a torrent label is set immediately after setting it
        delay(200)
      )
    }

    prep$.pipe(
      switchMap(_ => this.api.setTorrentLabel(this.id, {Label: suggestion.value}))
    ).subscribe(
      _ => this.ref.close(suggestion.value)
    )
  }
Example #25
Source File: rx-operators.ts    From ionic-pwa-example-moment with MIT License 6 votes vote down vote up
export function beforeEach<T, V>(valueBefore: V) {
  return (source$: Observable<T>) =>
    defer(() => {
      const subject$ = new ReplaySubject<V | T>(1);
      source$
        .pipe(
          // Force the source values emitted asynchronizingly.
          delay(0)
        )
        .subscribe({
          next: v => {
            subject$.next(valueBefore);
            subject$.next(v);
          },
          error: (err: unknown) => subject$.error(err),
          complete: () => subject$.complete(),
        });
      return subject$.pipe(
        // Make sure the values emitted asynchronizingly.
        concatMap(v => of(v).pipe(delay(0)))
      );
    });
}
Example #26
Source File: marble-test.spec.ts    From s-libs with MIT License 6 votes vote down vote up
describe('marbleTest()', () => {
  it('has fancy typing', () => {
    staticTest(() => {
      expectTypeOf(marbleTest(noop)).toEqualTypeOf<VoidFunction>();
      expectTypeOf(marbleTest(async () => 1)).toEqualTypeOf<
        () => Promise<number>
      >();
    });
  });

  // https://github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/testing/marble-testing.md
  it(
    'works for the first example in the docs',
    marbleTest(
      ({ cold, expectObservable, expectSubscriptions, testScheduler }) => {
        const e1 = cold(' -a--b--c---|');
        const subs = '    ^----------!';
        const expected = '-a-----c---|';

        expectObservable(e1.pipe(throttleTime(3, testScheduler))).toBe(
          expected,
        );
        expectSubscriptions(e1.subscriptions).toBe(subs);
      },
    ),
  );

  it(
    'works for two tests in a row',
    marbleTest(({ cold, expectObservable }) => {
      const input = ' -a-b-c|';
      const expected = '-- 9ms a 9ms b 9ms (c|)';

      const result = cold(input).pipe(concatMap((d) => of(d).pipe(delay(10))));

      expectObservable(result).toBe(expected);
    }),
  );
});
Example #27
Source File: data_service.ts    From profiler with Apache License 2.0 6 votes vote down vote up
captureProfile(options: CaptureProfileOptions):
      Observable<CaptureProfileResponse> {
    if (this.isLocalDevelopment) {
      return of({result: 'Done'});
    }
    const params =
        new HttpParams()
            .set('service_addr', options.serviceAddr)
            .set('is_tpu_name', options.isTpuName.toString())
            .set('duration', options.duration.toString())
            .set('num_retry', options.numRetry.toString())
            .set('worker_list', options.workerList)
            .set('host_tracer_level', options.hostTracerLevel.toString())
            .set('device_tracer_level', options.deviceTracerLevel.toString())
            .set('python_tracer_level', options.pythonTracerLevel.toString())
            .set('delay', options.delay.toString());
    return this.httpClient.get(this.pathPrefix + CAPTURE_PROFILE_API, {params});
  }
Example #28
Source File: star-wars.component.ts    From flingo with MIT License 6 votes vote down vote up
constructor(private cardService: CardService, private progress: ProgressService) {
        this.progress.isLoading(true);
        this.allCards$ = this.cards.pipe(
            delay(1000),
            tap(() => {
                this.progress.isLoading(false);
            })
        );
    }
Example #29
Source File: jwt-auth.service.ts    From matx-angular with MIT License 6 votes vote down vote up
public signin(username, password) {
    return of({token: DEMO_TOKEN, user: DEMO_USER})
      .pipe(
        delay(1000),
        map((res: any) => {
          this.setUserAndToken(res.token, res.user, !!res);
          this.signingIn = false;
          return res;
        }),
        catchError((error) => {
          return throwError(error);
        })
      );

    // FOLLOWING CODE SENDS SIGNIN REQUEST TO SERVER

    // this.signingIn = true;
    // return this.http.post(`${environment.apiURL}/auth/local`, { username, password })
    //   .pipe(
    //     map((res: any) => {
    //       this.setUserAndToken(res.token, res.user, !!res);
    //       this.signingIn = false;
    //       return res;
    //     }),
    //     catchError((error) => {
    //       return throwError(error);
    //     })
    //   );
  }