rxjs/operators#distinctUntilChanged TypeScript Examples

The following examples show how to use rxjs/operators#distinctUntilChanged. 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: EntityDataService.ts    From viewer-components-react with MIT License 7 votes vote down vote up
// Convenience method for retrieving selected observations queries (metric, unit, params) for a given sensor
  private getObservationQueriesForSensor$(id: string, returnFirstQueryOnly = false): Observable<ObservationQuery[]> {
    return IModelSettingsService.iModelSettings$()
      .pipe(
        map((iModelSettings: IModelSettings) => {
          return iModelSettings.getAssociation(id)?.getObservationQueries() || [];
        }),
        distinctUntilChanged((p: ObservationQuery[], c: ObservationQuery[]) => {
          return _isEqual(
            instanceToPlain(returnFirstQueryOnly ? p[0] : p),
            instanceToPlain(returnFirstQueryOnly ? c[0] : c)
          );
        })
      );
  }
Example #2
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 #3
Source File: slippage-settings.component.ts    From gnosis.1inch.exchange with MIT License 6 votes vote down vote up
ngOnInit(): void {

    console.log('set=' + this.slippage);
    this.selectSlippage(this.slippage);

    const slippageInput$ = this.slippageInput.valueChanges.pipe(
      filter((x) => !this.slippageInput.errors),
      map(x => {
        // In case user input empty string, take latest selected or maximal
        return x === ''
          ? this.slippageSelect.value || '3'
          : x;
      })
    );

    const slippageSelect$ = this.slippageSelect.valueChanges.pipe(
      filter(x => x !== 'custom')
    );

    this.subscription = merge(slippageSelect$, slippageInput$).pipe(
      distinctUntilChanged(),
      tap((latest: string) => {
        this.slippage = latest;
        this.slippageChange.next(latest);
      })
    ).subscribe();
  }
Example #4
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 #5
Source File: claimable-balances-dashboard.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #6
Source File: bridge-bottom-form.component.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
ngOnInit() {
    this.setupTradeCalculation();
    this.tradeStatus = TRADE_STATUS.DISABLED;

    this.bridgeService.tokens$.pipe(takeUntil(this.destroy$)).subscribe(tokens => {
      this.bridgeTokenPairsByBlockchainsArray = tokens;
    });

    this.swapFormService.inputValueChanges
      .pipe(
        startWith(this.swapFormService.inputValue),
        distinctUntilChanged((prev, next) => {
          return (
            prev.toBlockchain === next.toBlockchain &&
            prev.fromBlockchain === next.fromBlockchain &&
            prev.fromToken?.address === next.fromToken?.address &&
            prev.toToken?.address === next.toToken?.address &&
            prev.fromAmount === next.fromAmount
          );
        }),
        takeUntil(this.destroy$)
      )
      .subscribe(form => this.setFormValues(form));

    this.authService
      .getCurrentUser()
      .pipe(
        filter(user => !!user?.address),
        takeUntil(this.destroy$)
      )
      .subscribe(() => {
        this.setToWalletAddress();
        this.conditionalCalculate();
      });
  }
Example #7
Source File: list-cmd-flow.ts    From RcloneNg with MIT License 6 votes vote down vote up
public verify(cmd: string): Observable<CombErr<IRcloneServer>> {
		return this.getSupersetOutput().pipe(
			map(sup => {
				if (sup[1].length !== 0) return [{}, sup[1]] as any;
				if (-1 === sup[0].commands.findIndex(x => x.Path === cmd))
					return [{}, [new Error(`not support command: ${cmd}`)]];
				else return [{ url: sup[0].url, password: sup[0].password, user: sup[0].user }, []];
			}),
			distinctUntilChanged((x, y) => JSON.stringify(x) === JSON.stringify(y))
		);
	}
Example #8
Source File: shop-scanner.component.ts    From mylog14 with GNU General Public License v3.0 6 votes vote down vote up
ngOnInit() {
    this.couponService.reload();
    this.shopInfo$
      .pipe(
        filter(shopInfo => shopInfo.UUID !== ''),
        distinctUntilChanged((prev, curr) => prev.UUID === curr.UUID),
        tap(() => this.scanEnabled$.next(false)),
        switchMap(shopInfo => this.couponService.startRedeem(shopInfo)),
        tap(() => this.shopInfo$.next(this.defaultShopInfo)),
        tap(() => this.scanEnabled$.next(true)),
        takeUntil(this.destory$),
      ).subscribe();
  }
Example #9
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 #10
Source File: publish-message.component.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
constructor(private _formBuilder: FormBuilder) {
    this._messageClient = Beans.get(MessageClient);
    this._intentClient = Beans.get(IntentClient);

    this.form = this._formBuilder.group({
      [FLAVOR]: new FormControl(MessagingFlavor.Topic, Validators.required),
      [DESTINATION]: this.createTopicDestinationFormGroup(),
      [MESSAGE]: new FormControl(''),
      [HEADERS]: this._formBuilder.array([]),
      [REQUEST_REPLY]: new FormControl(false),
      [RETAIN]: new FormControl(false),
    });

    this.form.get(FLAVOR).valueChanges
      .pipe(
        startWith(this.form.get(FLAVOR).value as MessagingFlavor),
        distinctUntilChanged(),
        takeUntil(this._destroy$),
      )
      .subscribe((flavor: string) => {
        this.onFlavorChange(MessagingFlavor[flavor]);
      });
  }
Example #11
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 #12
Source File: mute.action.ts    From YTMD-StreamDeck with MIT License 6 votes vote down vote up
@SDOnActionEvent('willAppear')
    onContextAppear({ context }: WillAppearEvent) {
        this.socket.onTick$
            .pipe(distinctUntilChanged(), takeUntil(this.destroy$))
            .subscribe((data) => {
                if (Object.keys(data).length === 0) {
                    return;
                }
                const vol = data.player.volumePercent;
                MuteAction.currentVolume$.next(vol);
            });

        MuteAction.currentVolume$
            .pipe(distinctUntilChanged(), takeUntil(this.destroy$))
            .subscribe((vol) => {
                MuteAction.lastVolume = vol <= 0 ? MuteAction.lastVolume : vol;
                this.plugin.setTitle(
                    `${Math.round(
                        !vol || vol <= 0 ? 0 : vol >= 100 ? 100 : vol
                    )}%`,
                    context
                );
            });
    }
Example #13
Source File: dynamic-browser-title.service.ts    From nghacks with MIT License 6 votes vote down vote up
private init(): void {
    if (this._hasDynamicTitleServiceInitialized) {
      throw new Error('DynamicTitleService already initialized! Initialize it only once at the application bootstrap.');
    }
    this._router.events
      .pipe(
        filter((event) => event instanceof NavigationEnd),
        distinctUntilChanged()
      )
      .subscribe((route) => {
        this.check();
      });
    this._hasDynamicTitleServiceInitialized = true;
  }
Example #14
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 #15
Source File: router.component.ts    From router with MIT License 6 votes vote down vote up
ngOnInit() {
    combineLatest([this.routes$.pipe(debounceTime(1)), this.router.url$])
      .pipe(
        distinctUntilChanged(),
        tap(([routes, url]: [Route[], string]) => {
          let routeToRender = null;
          for (const route of routes) {
            routeToRender = this.isRouteMatch(url, route);

            if (routeToRender) {
              this.setRoute(url, route);
              break;
            }
          }

          if (!routeToRender) {
            this.setActiveRoute({ route: null, params: {}, path: '' });
          }
        }),
        takeUntil(this.destroy$)
      )
      .subscribe();
  }
Example #16
Source File: auth.state.ts    From auth0-angular with MIT License 6 votes vote down vote up
/**
   * Trigger used to pull User information from the Auth0Client.
   * Triggers when an event occurs that needs to retrigger the User Profile information.
   * Events: Login, Access Token change and Logout
   */
  private readonly isAuthenticatedTrigger$ = this.isLoading$.pipe(
    filter((loading) => !loading),
    distinctUntilChanged(),
    switchMap(() =>
      // To track the value of isAuthenticated over time, we need to merge:
      //  - the current value
      //  - the value whenever the access token changes. (this should always be true of there is an access token
      //    but it is safer to pass this through this.auth0Client.isAuthenticated() nevertheless)
      //  - the value whenever refreshState$ emits
      merge(
        defer(() => this.auth0Client.isAuthenticated()),
        this.accessTokenTrigger$.pipe(
          mergeMap(() => this.auth0Client.isAuthenticated())
        ),
        this.refresh$.pipe(mergeMap(() => this.auth0Client.isAuthenticated()))
      )
    )
  );
Example #17
Source File: contracts.ts    From webapp with MIT License 6 votes vote down vote up
contractAddresses$ = networkVars$.pipe(
  switchMapIgnoreThrow(networkVariables => {
    return fetchContractAddresses(networkVariables.contractRegistry).catch(() =>
      vxm.ethBancor.fetchContractAddresses(networkVariables.contractRegistry)
    );
  }),
  tap(x => {
    if (vxm && vxm.ethBancor) {
      vxm.ethBancor.setContractAddresses(x);
    }
  }),
  distinctUntilChanged<RegisteredContracts>(isEqual),
  shareReplay(1)
)
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: 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 #20
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 #21
Source File: fy-currency-choose-currency.component.ts    From fyle-mobile-app with MIT License 6 votes vote down vote up
ngAfterViewInit(): void {
    this.filteredCurrencies$ = fromEvent(this.searchBarRef.nativeElement, 'keyup').pipe(
      map((event: any) => event.srcElement.value),
      startWith(''),
      distinctUntilChanged(),
      switchMap((searchText) =>
        this.currencies$.pipe(
          map((currencies) =>
            currencies.filter(
              (currency) =>
                currency.shortCode.toLowerCase().includes(searchText.toLowerCase()) ||
                currency.longName.toLowerCase().includes(searchText.toLowerCase())
            )
          )
        )
      )
    );
  }
Example #22
Source File: data-view-table.component.ts    From geonetwork-ui with GNU General Public License v2.0 6 votes vote down vote up
tableData$ = combineLatest([
    this.compatibleDataLinks$,
    this.selectedLinkIndex$.pipe(distinctUntilChanged()),
  ]).pipe(
    map(([links, index]) => links[index]),
    switchMap((link) => {
      this.loading = true
      this.error = null
      return link
        ? this.fetchData(link).pipe(
            catchError((error) => {
              this.error = error.message
              return of([])
            }),
            finalize(() => {
              this.loading = false
            })
          )
        : of([])
    }),
    shareReplay(1)
  )
Example #23
Source File: client.ts    From js-client with MIT License 6 votes vote down vote up
private readonly _context$: Observable<APIContext> = combineLatest(
		this.host$,
		this.useEncryption$,
		this.authToken$,
	).pipe(
		map(([host, useEncryption, authToken]) => ({
			host,
			useEncryption,
			authToken,
			fetch: this._initialOptions.fetch ?? fetch,
		})),
		distinctUntilChanged((a, b) => isEqual(a, b)),
		shareReplay(1),
	);
Example #24
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 #25
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 #26
Source File: dept-tree-search.service.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
filteredData$ = combineLatest([
    this.originData$,
    this.searchValue$.pipe(
      debounceTime(200),
      distinctUntilChanged(),
      map(value => (this.searchValue = value))
    )
    // @ts-ignore
  ]).pipe(map(([data, value]) => (value ? this.filterTreeData(data as TreeNode[], value) : new FilteredTreeResult(data as TreeNode[]))));
Example #27
Source File: EntityDataService.ts    From viewer-components-react with MIT License 6 votes vote down vote up
// Convenience method for subscribing to the currently selected sensor
  private getSelectedSensorId$(): Observable<string | undefined> {
    return IModelSettingsService.iModelSettings$()
      .pipe(
        map((iModelSettings: IModelSettings) => {
          return iModelSettings.getSelectedEntityId();
        }),
        distinctUntilChanged((p: string | undefined, c: string | undefined) => {
          return p === c;
        })
      );
  }
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: form-tree-node.service.ts    From open-source with MIT License 6 votes vote down vote up
loaded$: Observable<boolean> = this._children$.pipe(
    startWith(null),
    switchMap(() => combineLatest([
      this._numChild$,
      this._loaded$,
      this._paramsLoaded$,
      ...this.children.map(child => child.loaded$),
    ])),
    map(([children, loadedComponent, loadedParams, ...childrenLoaded]) => {
      const isControl = this.instance === DynInstanceType.Control;
      const hasAllChildren = children === childrenLoaded.length;
      const allChildrenValid = childrenLoaded.every(Boolean);
      const allChildrenLoaded = this.instance === DynInstanceType.Control ? true : hasAllChildren && allChildrenValid;

      const result = Boolean(loadedComponent && loadedParams) && allChildrenLoaded;

      this.logger.nodeLoad(this, !isControl
        ? { loaded$: result, loadedComponent, loadedParams, children, childrenLoaded }
        : { loaded$: result, loadedComponent, loadedParams }
      );

      return result;
    }),
    distinctUntilChanged(),
    shareReplay(1),
  );