rxjs/operators#debounceTime TypeScript Examples

The following examples show how to use rxjs/operators#debounceTime. 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: home.component.ts    From one-platform with MIT License 6 votes vote down vote up
ngOnInit(): void {
    this.searchControl
      .pipe(debounceTime(300), distinctUntilChanged())
      .subscribe({
        next: (searchTerm: string) => {
          this.debouncedSearchProject = searchTerm;
        },
      });
    this.dashboardServiceSub = this.dashboardService
      .listLHProjects()
      .subscribe(({ data, loading }) => {
        this.isProjectListLoading = loading;
        this.projects = data.listLHProjects;
        this.isEmpty = data.listLHProjects.count === 0;
      });
  }
Example #2
Source File: queryable-input.component.ts    From Smersh with MIT License 6 votes vote down vote up
ngOnInit(): void {
    Object.entries(this.input ?? {}).map(([k, v]) => {
      this[k.toString()] = v;
    });
    this.queryableInputControl.valueChanges
      .pipe(debounceTime(500), distinctUntilChanged())
      .subscribe((v) => {
        if (v.value) {
          return;
        }
        this.fetch({ [this.source]: v });
      });
    this.fetch();
  }
Example #3
Source File: watch-assets.ts    From codedoc with MIT License 6 votes vote down vote up
export function watchAssets(root: string, config: CodedocConfig, state: BehaviorSubject<{status: Status}>) {
  const change$ = new Subject<string>();

  watch(join(root, config.dest.assets), {
    recursive: true,
    filter: f => ASSET_EXTENSIONS.some(extension => f.toLowerCase().endsWith(extension))
  }, (_, filename) => change$.next(filename));

  return change$.pipe(
    debounceTime(10),
    filter(() => state.value.status !== StatusBuildingResponse)
  );
}
Example #4
Source File: chatkitty.ts    From chatkitty-js with MIT License 6 votes vote down vote up
public constructor(private readonly configuration: ChatKittyConfiguration) {
    this.stompX = new StompX({
      isSecure: configuration.isSecure === undefined || configuration.isSecure,
      host: configuration.host || 'api.chatkitty.com',
      isDebug: !environment.production,
    });

    this.keyStrokesSubject
      .asObservable()
      .pipe(debounceTime(150))
      .subscribe((request) => {
        let destination = ''

        const channel = (request as SendChannelKeystrokesRequest).channel;
        const thread = (request as SendThreadKeystrokesRequest).thread;

        if (channel) {
          destination = channel._actions.keystrokes
        }

        if (thread) {
          destination = thread._actions.keystrokes
        }

        this.stompX.sendAction<never>({
          destination,
          body: {
            keys: request.keys,
          },
        });
      });
  }
Example #5
Source File: claimable-balance-details.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
buttonTriggeredSubscription: Subscription = this.buttonTriggered$
    .asObservable()
    .pipe(debounceTime(100))
    .pipe(takeUntil(this.componentDestroyed$))
    .subscribe(async type => {
      this.disableActionButtons$.next(true);
      try {
        await this.onClaim(type);
      } catch (e) {
        console.error(e);
      }
      this.disableActionButtons$.next(false);
    });
Example #6
Source File: tokens-api.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Fetch specific tokens from backend.
   * @param params Request params.
   * @param tokensNetworkState$ Tokens pagination state.
   * @return Observable<List<Token>> Tokens list.
   */
  public getTokensList(
    params: { [p: string]: unknown },
    tokensNetworkState$: BehaviorSubject<TokensNetworkState>
  ): Observable<List<Token>> {
    return this.iframeService.isIframe$.pipe(
      debounceTime(50),
      switchMap(isIframe => {
        return isIframe
          ? this.fetchIframeTokens(params)
          : this.fetchBasicTokens(tokensNetworkState$);
      })
    );
  }
Example #7
Source File: echarts.component.ts    From ng-devui-admin with MIT License 6 votes vote down vote up
ngAfterViewInit(): void {
    if (!this.theme && this.themeService && this.themeService.eventBus) {
      this.themeService.eventBus.add('themeChanged', this.themeChange);
    }
    this.initTheme();
    this.echart = (<any>echarts).init(this.elementRef.nativeElement, this.theme);
    this.updateChartData(this.options);
    this.chartReady.emit(this.echart);
    // 根据浏览器大小变化自动调整echarts
    if (this.autoResize) {
      this.resizeSub = fromEvent(window, 'resize')
        .pipe(debounceTime(100))
        .subscribe(() => {
          this.echart.resize();
        });
    }
  }
Example #8
Source File: bill-of-materials.component.ts    From barista with Apache License 2.0 6 votes vote down vote up
ngAfterViewInit(): void {
    if (!this.searchInput) {
      return;
    }

    fromEvent(this.searchInput.nativeElement, 'input')
      .pipe(
        map((event: any) => event.target.value),
        filter(res => res.length > 2 || res.length === 0),
        debounceTime(500),
        distinctUntilChanged(),
        untilDestroyed(this),
      )
      .subscribe((text: string) => {
        this.bomGlobalFilterMessageService.send(text);
      });
  }
Example #9
Source File: home.component.ts    From Angular-Cookbook with MIT License 6 votes vote down vote up
ngOnInit() {
    this.componentAlive = true;
    this.searchForm = new FormGroup({
      username: new FormControl('', []),
    });
    this.searchUsers();
    this.searchForm
      .get('username')
      .valueChanges.pipe(
        takeWhile(() => !!this.componentAlive),
        debounceTime(300)
      )
      .subscribe(() => {
        this.searchUsers();
      });
  }
Example #10
Source File: grocy-api.component.ts    From pantry_party with Apache License 2.0 6 votes vote down vote up
ngOnInit(): void {
    merge(
      this.form.valueChanges,
      this.forceCheck
    ).pipe(
      tap(() => this.updateValidationStatus()),
      takeUntil(this.ngUnsubscribe),
      debounceTime(250),
      filter(() =>  this.form.valid),
      tap(() => this.working = true),
      switchMap(_ => this.grocyService.getSystemInfo(
        this.formControl("url").value,
        this.formControl("apiKey").value
      ).pipe(
      map(r => ({result: "success" as "success", resp: r})),
      catchError((e: HttpErrorResponse) => of({result: "error" as "error", err: e}))
      )),
      tap(() => this.working = false)
    ).subscribe(r =>  this.renderReturn(r));

    if (this.form.valid) {
      this.forceCheck.next(true);
    }
  }
Example #11
Source File: ɵclient.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
/**
   * Monitors the heartbeat of this client to detect when this client is no longer connected to the host.
   * When not receiving any more heartbeat, this client will be marked as stale and queued for removal.
   *
   * A client may fail to disconnect from the broker for a number of reasons:
   * - The client was disposed without notice, i.e., without receiving the browser's "unload" event.
   * - The browser discarded the "DISCONNECT" message because the client window became stale.
   *   Typically, the browser discards messages for windows that are already closed or if another page
   *   has been loaded into the window, both indicating a high load on the client during unloading.
   */
  private installHeartbeatMonitor(): void {
    // The host app client does not send a heartbeat.
    if (this.application.symbolicName === Beans.get(APP_IDENTITY)) {
      return;
    }

    // Only clients of version 1.0.0-rc.1 or greater send a heartbeat.
    if (semver.lt(this.version, '1.0.0-rc.1')) {
      Beans.get(Logger).warn(`[VersionMismatch] Since '@scion/[email protected]', connected clients must send a heartbeat to indicate liveness. Please upgrade @scion/microfrontend-platform of application '${this.application.symbolicName}' from version '${this.version}' to version '${Beans.get(VERSION)}'.`, new LoggingContext(this.application.symbolicName, this.version));
      return;
    }

    this._heartbeat = Beans.get(MessageClient).observe$(PlatformTopics.heartbeat(this.id))
      .pipe(
        filter(message => message.headers.get(MessageHeaders.ClientId) === this.id),
        startWith(undefined as void),
        debounceTime(2 * this._heartbeatInterval),
      )
      .subscribe(() => {
        this.logStaleClientWarning();
        Beans.get(ClientRegistry).unregisterClient(this);
      });
  }
Example #12
Source File: alert-list.component.ts    From VIR with MIT License 6 votes vote down vote up
ngOnInit() {
    this.subscribeToData()

    this.searchQueryChangeSubscription = this.searchQueryValue.pipe(
      debounceTime(SEARCH_IDLE_DELAY),
    ).subscribe((value) => {
      this.refresh()
    })
  }
Example #13
Source File: my-addons.component.ts    From WowUp with GNU General Public License v3.0 6 votes vote down vote up
public ngAfterViewInit(): void {
    this._sessionService.myAddonsCompactVersion = !this.getLatestVersionColumnVisible();

    if (this.addonFilter?.nativeElement !== undefined) {
      const addonFilterSub = fromEvent(this.addonFilter.nativeElement as HasEventTargetAddRemove<unknown>, "keyup")
        .pipe(
          filter(Boolean),
          debounceTime(200),
          distinctUntilChanged(),
          tap(() => {
            const val: string = this.addonFilter.nativeElement.value.toString();
            console.debug(val);
            this._filterInputSrc.next(val);
          })
        )
        .subscribe();

      this._subscriptions.push(addonFilterSub);
    }

    this._sessionService.autoUpdateComplete$
      .pipe(
        tap(() => console.log("Checking for addon updates...")),
        switchMap(() => from(this.loadAddons()))
      )
      .subscribe(() => {
        this._cdRef.markForCheck();
      });
  }
Example #14
Source File: overflow-carousel.component.ts    From nghacks with MIT License 6 votes vote down vote up
public ngAfterViewInit(): void {

    const resizedEvents: EventEmitter<ResizedEvent>[] = this._resizedDirectives.map(directive => directive.resized);

    merge(...resizedEvents)
      .pipe(
        takeUntil(this._unsubscribeAll),
        debounceTime(100)
      )
      .subscribe((ev: ResizedEvent) => {
        this._containerWidth = this._carouselContainerElementRef.nativeElement.clientWidth;
        this._contentWidth = this._carouselElementRef.nativeElement.clientWidth;
        this.carouselPosition = this._carouselPosition;
      });
  }
Example #15
Source File: filter-by-number.component.ts    From ngx-admin-dotnet-starter with MIT License 6 votes vote down vote up
ngOnInit() {
    this.inputControl.valueChanges
      .pipe(
        distinctUntilChanged(),
        debounceTime(this.delay),
      )
      .subscribe((value: number) => {
        this.query = value !== null ? this.inputControl.value.toString() : '';
        this.setFilter();
      });
  }
Example #16
Source File: book.effects.ts    From router with MIT License 6 votes vote down vote up
search$ = createEffect(
    () =>
      ({ debounce = 300, scheduler = asyncScheduler } = {}) =>
        this.actions$.pipe(
          ofType(FindBookPageActions.searchBooks),
          debounceTime(debounce, scheduler),
          switchMap(({ query }) => {
            if (query === '') {
              return empty;
            }

            const nextSearch$ = this.actions$.pipe(
              ofType(FindBookPageActions.searchBooks),
              skip(1)
            );

            return this.googleBooks.searchBooks(query).pipe(
              takeUntil(nextSearch$),
              map((books: Book[]) => BooksApiActions.searchSuccess({ books })),
              catchError((err) =>
                of(BooksApiActions.searchFailure({ errorMsg: err.message }))
              )
            );
          })
        )
  );
Example #17
Source File: page-tabs.component.ts    From t3mpl-editor with MIT License 6 votes vote down vote up
public ngOnInit() {
		merge(
			this.stateService.onStateChanged,
			this.stateService.onPageChanged,
			this.stateService.onConfigurationChanged,
			this.stateService.onPreviewModeChanged
		)
		.pipe(debounceTime(50))
		.subscribe(() => this.reload());
	}
Example #18
Source File: expenses.component.ts    From budget-angular with GNU General Public License v3.0 6 votes vote down vote up
ngAfterViewInit() {
    this.keyupSubscription = fromEvent(this.filter.nativeElement, "keyup")
      .pipe(
        debounceTime(1000),
        map((event: Event) => (<HTMLInputElement>event.target).value),
        distinctUntilChanged(),
        tap(() => (this.isLoading = true)),
        switchMap((value) =>
          this.expensesService.filterExpenses(this.period, value)
        )
      )
      .subscribe((data) => {
        this.isLoading = false;
        this.dataSource.data = data;
      });
  }
Example #19
Source File: send.component.ts    From blockcore-hub with MIT License 6 votes vote down vote up
private buildSendForm(): void {
        this.sendForm = this.fb.group({
            address: ['', Validators.compose([Validators.required, Validators.minLength(26)])],
            amount: ['', Validators.compose([Validators.required, Validators.pattern(/^([0-9]+)?(\.[0-9]{0,8})?$/), Validators.min(0.00001), (control: AbstractControl) => Validators.max((this.totalBalance - this.estimatedFee) / 100000000)(control)])],
            fee: ['medium', Validators.required],
            password: ['', Validators.required],
            shuffleOutputs: [true],
            opreturndata: ['', Validators.compose([Validators.maxLength(this.appState.activeChain.opreturndata)])], // TODO: This is maxLength for ASCII, with UNICODE it can be longer but node will throw error then. Make a custom validator that encodes UTF8 to bytes.
            opreturnamount: ['', Validators.compose([Validators.pattern(/^([0-9]+)?(\.[0-9]{0,8})?$/)])],
        });

        this.sendForm.valueChanges.pipe(debounceTime(300))
            .subscribe(data => this.onValueChanged(data));
    }
Example #20
Source File: contact-form.component.ts    From careydevelopmentcrm with MIT License 6 votes vote down vote up
private handleBasicInfoFormSubscription() {
    //tracks changes to the form
    //if the form becomes invalid, this will light the icon button red
    //if the invalid form becomes valid, it will turn the icon button to original color
    this.basicInfoFormSubscription = this.basicInfoComponent
      .basicInfoFormGroup
      .valueChanges
      .pipe(
        debounceTime(500),
        distinctUntilChanged()
      )
      .subscribe(
        (values) => {
          this.handleFormCheck();
        }
      );
  }
Example #21
Source File: notes-editor.component.ts    From attack-workbench-frontend with Apache License 2.0 6 votes vote down vote up
ngAfterViewInit() {
        // search input listener
        fromEvent(this.search.nativeElement, 'keyup').pipe(
            filter(Boolean),
            debounceTime(250),
            distinctUntilChanged(),
            tap(_ => { this.parseNotes(); })
        ).subscribe();
    }
Example #22
Source File: send.component.ts    From EXOS-Core with MIT License 6 votes vote down vote up
private buildSendForm(): void {
        this.sendForm = this.fb.group({
            address: ['', Validators.compose([Validators.required, Validators.minLength(26)])],
            amount: ['', Validators.compose([Validators.required, Validators.pattern(/^([0-9]+)?(\.[0-9]{0,8})?$/), Validators.min(0.00001), (control: AbstractControl) => Validators.max((this.totalBalance - this.estimatedFee) / 100000000)(control)])],
            fee: ['medium', Validators.required],
            password: ['', Validators.required]
        });

        this.sendForm.valueChanges.pipe(debounceTime(300))
            .subscribe(data => this.onValueChanged(data));
    }
Example #23
Source File: add-edit-mileage.page.ts    From fyle-mobile-app with MIT License 6 votes vote down vote up
setupDuplicateDetection() {
    this.duplicates$ = this.fg.valueChanges.pipe(
      debounceTime(1000),
      distinctUntilChanged((a, b) => isEqual(a, b)),
      switchMap(() => this.getPossibleDuplicates())
    );

    this.duplicates$
      .pipe(
        filter((duplicates) => duplicates && duplicates.length),
        take(1)
      )
      .subscribe((res) => {
        this.pointToDuplicates = true;
        setTimeout(() => {
          this.pointToDuplicates = false;
        }, 3000);

        this.etxn$.pipe(take(1)).subscribe(async (etxn) => await this.trackDuplicatesShown(res, etxn));
      });
  }
Example #24
Source File: autocomplete.component.ts    From geonetwork-ui with GNU General Public License v2.0 6 votes vote down vote up
ngOnInit(): void {
    this.suggestions$ = this.control.valueChanges.pipe(
      filter((value) => value.length > 2),
      debounceTime(400),
      distinctUntilChanged(),
      tap(() => (this.searching = true)),
      switchMap((value) => this.action(value)),
      finalize(() => (this.searching = false))
    )
    this.subscription = this.control.valueChanges.subscribe((any) => {
      if (any !== '') {
        this.cancelEnter = false
      }
    })
    this.control.valueChanges
      .pipe(filter((value) => typeof value === 'string'))
      .subscribe(this.lastInputValue$)
  }
Example #25
Source File: color-canvas.component.ts    From angular-material-components with MIT License 6 votes vote down vote up
ngOnInit() {

    const rgbaCtrl$ = merge(this.rCtrl.valueChanges, this.gCtrl.valueChanges,
      this.bCtrl.valueChanges, this.aCtrl.valueChanges);
    rgbaCtrl$.pipe(takeUntil(this._destroyed), debounceTime(400), distinctUntilChanged())
      .subscribe(_ => {
        const color = new Color(Number(this.rCtrl.value),
          Number(this.gCtrl.value), Number(this.bCtrl.value), Number(this.aCtrl.value));
        this.emitChange(color);
      });

    const hexCtrl$ = this.hexCtrl.valueChanges;
    hexCtrl$.pipe(takeUntil(this._destroyed), debounceTime(400), distinctUntilChanged())
      .subscribe(hex => {
        const obj = stringInputToObject(hex);
        if (obj != null) {
          const color = new Color(obj.r, obj.g, obj.b, obj.a);
          this.emitChange(color);
        }
      })
  }
Example #26
Source File: heatmap.component.ts    From avid-covider with MIT License 6 votes vote down vote up
constructor(public layout: LayoutService, public mapService: MapService, private i18n: I18nService,
              private storage: ReportStoreService, @Inject(LOCALE_ID) private locale) {
    this.popupStream.pipe(
      debounceTime(250),
      distinctUntilChanged((prev, curr) => prev.city_id === curr.city_id),
    ).subscribe((ev) => {
      this.popupVisible = !!ev.city_id;
      if (this.popupVisible) {
        this.popupLeft = (this.padding + ev.location.x) + 'px';
        this.popupTop = (this.padding + ev.location.y) + 'px';
        this.popupData = this.mapService.popup_data[ev.city_id] || {};

        this.popupData.txCityName = this.popupData.translations ?
          (this.popupData.translations[this.locale] || this.popupData.translations.he) :
          this.popupData.city_name;
      }
    });
  }
Example #27
Source File: lazy-scroll.component.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
ngAfterViewInit(): void {
    this.lazyServiceService.adHost = this.adHost;
    this.zone.runOutsideAngular(() => {
      fromEvent(window, 'scroll', <AddEventListenerOptions>passiveEventListenerOptions).pipe(
        debounceTime(50),
        filter(() => {
          return window.scrollY >= 200;
        }),
        take(1),
        takeUntil(this.destroyService$)
      ).subscribe(() => {
        this.lazyServiceService.create().then(()=>{
          this.cdr.detectChanges();
        })
      })
    })
  }
Example #28
Source File: hero-search.component.ts    From angular-dream-stack with MIT License 6 votes vote down vote up
ngOnInit(): void {
    this.heroes$ = this.searchTerms.pipe(
      // wait 300ms after each keystroke before considering the term
      debounceTime(300),

      // ignore new term if same as previous term
      distinctUntilChanged(),

      // switch to new search observable each time the term changes
      switchMap((term: string) => this.heroService.searchHeroes(term))
    );
  }
Example #29
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();
    }