rxjs/operators#startWith TypeScript Examples

The following examples show how to use rxjs/operators#startWith. 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: app.component.ts    From gnosis.1inch.exchange with MIT License 7 votes vote down vote up
private getFilteredTokens(form: FormControl): Observable<ITokenDescriptor[]> {

        return combineLatest([
            this.sortedTokens$,
            form.valueChanges.pipe(
                startWith('')
            ),
        ]).pipe(
            map((x) => {
                const [tokens, filterText] = x;
                return filterTokens(tokens, filterText);
            })
        );
    }
Example #2
Source File: option-selector.component.ts    From 1x.ag with MIT License 6 votes vote down vote up
async initOptionSearchResults() {

        this.optionSearchResults = this.optionSearchControl.valueChanges.pipe(
            startWith(''),
            map(term => {

                const result = Object.values(this.options);

                if (term !== '') {

                    return result
                        .filter(v => {

                            return (v['name']
                                .toLowerCase()
                                .indexOf(term.toLowerCase()) > -1);

                        })
                        .slice(0, 10);
                }

                return result;
            })
        );
    }
Example #3
Source File: gas-settings.component.ts    From gnosis.1inch.exchange with MIT License 6 votes vote down vote up
ngOnInit(): void {

    this.gasPrice$ = this.txSpeedSelect.valueChanges.pipe(
      switchMap((txSpeed: TxSpeed) => {
        console.log(`txSpeed=`, txSpeed);
        if (txSpeed !== 'custom') {
          return of(this.getGasPrice(txSpeed));
        }

        return this.gasPriceInput.valueChanges.pipe(
            startWith(this.gasPriceInput.value),
            filter(() => !this.gasPriceInput.errors),
            map((value) => {
              this.customGasPrice = value;
              return [formatGasPrice(value), value];
            })
          );

      }),
      map(([gasPriceBN, gasPrice]) => {
        this.gasPriceChange.next({
          gasPriceBN,
          gasPrice,
          txSpeed: this.txSpeedSelect.value
        });
        return gasPrice;
      }),
      shareReplay({ bufferSize: 1, refCount: true })
    );

    this.subscription.add(
      this.gasPrice$.subscribe()
    );
  }
Example #4
Source File: component.tsx    From codedoc with MIT License 6 votes vote down vote up
export function HintBox(
  this: ThemedComponentThis<CodedocTheme>,
  _: any, 
  renderer: any
) {
  const classes = this.theme.classes(HintBoxStyle);
  const target$ = this.expose.in('target', new Subject<HTMLElement | undefined>());
  const active$ = target$.pipe(map(el => !!el));
  const top$ = combineLatest(
      target$
        .pipe(
          map(el => el ? el.getBoundingClientRect().top : undefined)
        ), 
      fromEvent(document, 'mousemove')
        .pipe(
          map(e => (e as MouseEvent).clientY)
        )
    ).pipe(
      map(([top, mouseY]) => (top || mouseY) + 24)
    );
  const left$ = fromEvent(document, 'mousemove').pipe(map(e => (e as MouseEvent).clientX + 24));

  return <div 
      class={rl`${classes.hintbox} ${toggleList({'active': active$.pipe(startWith(false))})}`}
      style={rl`top: ${top$}px;left: ${left$}px`}
    >
    <span class="icon-font outline">wb_incandescent</span>
    {target$.pipe(filter(el => !!el), map(el => el?.getAttribute('data-hint')))}
  </div>;
}
Example #5
Source File: layout-v1-account-horizon-selector.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
walletAccountsPublicKeys$ = this.walletSelectControl
    .valueChanges
    .pipe(startWith(this.walletsQuery.getActive()?._id))
    .pipe(switchMap(walletId =>
      this.walletsAccountsQuery.selectAll({ filterBy: entity => entity.walletId === walletId })
    ))
    .pipe(map(accounts =>
      accounts.reduce((all: { [x: string]: IWalletsAccount }, current) =>
          all[current.publicKey] ? all : ({ ...all, [current.publicKey]: current })
        , {})
    ))
    .pipe(map(data => Object.values(data)));
Example #6
Source File: deposit-form.component.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
public readonly brbcAmount$ = this.brbcAmountCtrl.valueChanges.pipe(
    startWith(this.brbcAmountCtrl.value),
    map(value => this.lpService.parseInputValue(value)),
    tap(async amount => {
      const amountUsdPrice = await this.lpService.calculateBrbcUsdPrice(new BigNumber(amount));
      this._rbcAmountUsdPrice$.next(amountUsdPrice);
    }),
    takeUntil(this.destroy$)
  );
Example #7
Source File: index.ts    From dbm with Apache License 2.0 6 votes vote down vote up
manifest$ = merge(
  ...Object.entries({
    "**/*.scss": stylesheets$,
    "**/*.ts*":  javascripts$
  })
    .map(([pattern, observable$]) => (
      defer(() => process.argv.includes("--watch")
        ? watch(pattern, { cwd: "src" })
        : EMPTY
      )
        .pipe(
          startWith("*"),
          switchMapTo(observable$.pipe(toArray()))
        )
    ))
)
  .pipe(
    scan((prev, mapping) => (
      mapping.reduce((next, [key, value]) => (
        next.set(key, value.replace(`${base}/`, ""))
      ), prev)
    ), new Map<string, string>()),
  )
Example #8
Source File: home.component.ts    From Angular-Cookbook with MIT License 6 votes vote down vote up
listenToInputChanges() {
    this.boxStyles$ = combineLatest([
      this.boxForm
        .get('size')
        .valueChanges.pipe(startWith(this.sizeOptions[0])),
      this.boxForm
        .get('borderRadius')
        .valueChanges.pipe(startWith(this.borderRadiusOptions[0])),
      this.boxForm
        .get('backgroundColor')
        .valueChanges.pipe(startWith(this.colorOptions[1])),
      this.boxForm
        .get('textColor')
        .valueChanges.pipe(startWith(this.colorOptions[0])),
    ]).pipe(
      map(([size, borderRadius, backgroundColor, textColor]) => {
        return {
          width: `${size}px`,
          height: `${size}px`,
          backgroundColor,
          color: textColor,
          borderRadius: `${borderRadius}px`,
        };
      })
    );
  }
Example #9
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 #10
Source File: get-bg-class.pipe.ts    From colo-calc with Do What The F*ck You Want To Public License 6 votes vote down vote up
public transform(control: FormControl): Observable<ReturnType> {
    return control.valueChanges.pipe(
      startWith(control.value),
      map((value: ClassKey) => {
        const code: ClassKey = (value as ClassKey)|| Background.Solid;
        console.log(code, valueToClassName[code]);
        return { [valueToClassName[code]]: true };
      })
    )
  }
Example #11
Source File: link-active.directive.ts    From router with MIT License 6 votes vote down vote up
collectLinks() {
    if (this._linksSub) {
      this._linksSub.unsubscribe();
    }

    const contentLinks$ = this.links
      ? this.links.toArray().map((link) =>
          link.hrefUpdated.pipe(
            startWith(link.linkHref),
            map(() => link.linkHref),
            filterNullable()
          )
        )
      : [];

    const link$ = this.link
      ? this.link.hrefUpdated.pipe(
          startWith(this.link.linkHref),
          map(() => this.link.linkHref),
          filterNullable()
        )
      : of('');

    const router$ = this.router.url$.pipe(
      map((path) => this.router.getExternalUrl(path || '/'))
    );

    const observables$ = [router$, link$, ...contentLinks$];

    this._linksSub = combineLatest(observables$)
      .pipe(takeUntil(this._destroy$))
      .subscribe(([path, link, ...links]) => {
        this.checkActive([...links, link], path);
      });
  }
Example #12
Source File: course.component.ts    From reactive-angular-course with MIT License 6 votes vote down vote up
ngOnInit() {

        const courseId = parseInt(this.route.snapshot.paramMap.get("courseId"));

        const course$ = this.coursesService.loadCourseById(courseId)
            .pipe(
                startWith(null)
            );

        const lessons$ = this.coursesService.loadAllCourseLessons(courseId)
            .pipe(
                startWith([])
            );

        this.data$ = combineLatest([course$, lessons$])
            .pipe(
                map(([course, lessons]) => {
                    return {
                        course,
                        lessons
                    }
                }),
                tap(console.log)
            );


  }
Example #13
Source File: gps-dialog.ts    From ASW-Form-Builder with MIT License 6 votes vote down vote up
async ngOnInit(): Promise<void> {
        this.validateFormBuilder();
        this.searchedAddress = await this.googleMapService.getNearestAddress();
        this.editProperty(this.control);
        this.aswEditGpsForm.get('value')?.valueChanges.pipe(
            startWith(''),
            map(address => (address)),
        ).subscribe(async address => {
            await this.searchAddressFromExitingData(address);
        });
    }
Example #14
Source File: customOperators.ts    From webapp with MIT License 6 votes vote down vote up
optimisticContract =
  (key: string) => (source: Observable<string>) => {
    const cachedData = localStorage.getItem(key);

    if (cachedData) {
      return source.pipe(
        startWith(cachedData),
        distinctUntilChanged(compareString),
        tap(data => {
          const isSame = cachedData === data;
          if (!isSame) {
            localStorage.setItem(key, data);
          }
        })
      );
    } else {
      return source.pipe(
        distinctUntilChanged(compareString),
        tap(data => localStorage.setItem(key, data))
      );
    }
  }
Example #15
Source File: search-torrents.component.ts    From qbit-matUI with MIT License 6 votes vote down vote up
ngOnInit(): void {

    // Detect any changes to torrrent data & update options accordingly
    this.data_store.GetTorrentDataSubscription().subscribe(res => {

      if(res) { this._updateOptions(res.torrents); }
    });

    this.filteredOptions = this.myControl.valueChanges
    .pipe(
      startWith(''),
      map(val => this._filter(val))
    )
  }
Example #16
Source File: api.service.ts    From blockcore-hub with MIT License 6 votes vote down vote up
getNodeStatusInterval(): Observable<any> {
        const self = this;

        return interval(this.pollingInterval)
            .pipe(startWith(0))
            .pipe(switchMap(() => this.http.get(self.apiUrl + '/node/status', { headers: self.headers })))
            .pipe(catchError(this.handleError.bind(this)))
            .pipe(map((response: Response) => response));
    }
Example #17
Source File: user-menu.component.ts    From angular-component-library with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
ngOnInit(): void {
        requireInput<UserMenuComponent>(['open'], this);

        // Subscribe to resize events and transition from menu to bottomsheet (or vise versa) when open & resizing
        this.screenSizeChangeListener = fromEvent(window, 'resize')
            .pipe(map(this.checkScreenSize))
            .pipe(startWith(this.checkScreenSize()))
            .subscribe((isMobile: boolean) => {
                // Transition from Desktop to Mobile
                if (this.open && isMobile && !this.useBottomSheet) {
                    this.isMenuOpen = false;
                    this.openBottomSheet();
                    this._ref.detectChanges();
                }
                // Transition from Mobile to Desktop
                else if (this.open && !isMobile && this.useBottomSheet) {
                    this._bottomSheet.dismiss(true);
                }
                this.useBottomSheet = isMobile;
            });
    }
Example #18
Source File: api.service.ts    From EXOS-Core with MIT License 6 votes vote down vote up
getNodeStatusInterval(): Observable<any> {
        const self = this;

        return interval(this.pollingInterval)
            .pipe(startWith(0))
            .pipe(switchMap(() => this.http.get(self.apiUrl + '/node/status', { headers: self.headers })))
            .pipe(catchError(this.handleError.bind(this)))
            .pipe(map((response: Response) => response));
    }
Example #19
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 #20
Source File: subscribe-to-one-raw-search.ts    From js-client with MIT License 6 votes vote down vote up
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 #21
Source File: app.component.ts    From aws-power-tuner-ui with Apache License 2.0 6 votes vote down vote up
startPolling(token: PowerTunerToken) {
    this.executionToken = token.executionToken;
    this.formGroup.controls.executionId.setValue(this.executionToken);
    localStorage.setItem('token', this.executionToken);

    const subject = new Subject<string>();
    let attempt = 0;
    this.trackedSubscriptions.push(interval(5000)
      .pipe(
        startWith(0),
        take(24),
        takeUntil(subject),
        switchMap(() => this.httpService.fetchPowerTunerStepFunction(token))
      )
      .subscribe(
        ratesResult => {
          attempt += 1;
          if (this.checkStatusToEndPolling(ratesResult.status)) {
            if (ratesResult.status === 'SUCCEEDED') {
              this.processResults(JSON.parse(ratesResult.output));
              this.resultsBack = true;
              this.resultsProcessing = false;
            } else {
              this.resultsError = true;
              this.resetTuner();
            }
            subject.next('Finished');
          }
          if (attempt >= 24) {
            subject.next('Finished');
          }
        },
        error => {
          this.processErrorResults(error);
          subject.next('Error');
        }
      ));
  }
Example #22
Source File: simple.component.ts    From open-source with MIT License 6 votes vote down vote up
ngAfterViewInit(): void {
    // logs each change in the console just to demo
    this.dynForm.valueChanges().subscribe(console.log);

    // simple example of how we can trigger changes into the params
    const group = this.form.get('billing') as FormGroup;
    group.statusChanges.pipe(startWith(group.status)).subscribe((status) => {
      this.profileCard.next({
        title: 'Billing Address',
        subtitle:
          status === 'INVALID'
            ? 'Please fill your Personal Information'
            : 'Billing information complete',
      });
    });
  }
Example #23
Source File: page-visibility.ts    From common with MIT License 6 votes vote down vote up
PAGE_VISIBILITY = new InjectionToken<Observable<boolean>>(
    'Shared Observable based on `document visibility changed`',
    {
        factory: () => {
            const documentRef = inject(DOCUMENT);

            return fromEvent(documentRef, 'visibilitychange').pipe(
                startWith(0),
                map(() => documentRef.visibilityState !== 'hidden'),
                distinctUntilChanged(),
                share(),
            );
        },
    },
)
Example #24
Source File: home.page.ts    From capture-lite with GNU General Public License v3.0 6 votes vote down vote up
readonly hasNewInbox$ = this.diaBackendTransactionRepository.inbox$.pipe(
    catchError((err: unknown) => this.errorService.toastError$(err)),
    map(transactions => transactions.count !== 0),
    /**
     * WORKARDOUND: force changeDetection to update badge when returning to App
     * by clicking push notification
     */
    tap(() => this.changeDetectorRef.detectChanges()),
    startWith(false)
  );
Example #25
Source File: deposit-form.component.ts    From digital-bank-ui with Mozilla Public License 2.0 6 votes vote down vote up
constructor(private formBuilder: FormBuilder, private accountingService: AccountingService, private route: ActivatedRoute) {
    this.productForm = this.formBuilder.group({
      identifier: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(32), FimsValidators.urlSafe]],
      type: ['', [Validators.required]],
      name: ['', [Validators.required, Validators.maxLength(256)]],
      description: ['', Validators.maxLength(2048)],
      currencyCode: ['', [Validators.required]],
      minimumBalance: ['', [Validators.required]],
      fixedTermEnabled: [false],
      interest: ['', [Validators.required, FimsValidators.minValue(0)]],
      flexible: [{ value: '', disabled: this.editMode }, [Validators.required]],
      termPeriod: [''],
      termTimeUnit: [''],
      termInterestPayable: ['', [Validators.required]],
      cashAccountIdentifier: ['', [Validators.required], accountExists(this.accountingService)],
      expenseAccountIdentifier: ['', [Validators.required], accountExists(this.accountingService)],
      equityLedgerIdentifier: ['', [Validators.required], ledgerExists(this.accountingService)],
      accrueAccountIdentifier: ['', [Validators.required], accountExists(this.accountingService)],
    });

    this.termChangeSubscription = this.productForm
      .get('fixedTermEnabled')
      .valueChanges.pipe(startWith(null))
      .subscribe(enabled => this.toggleFixedTerm(enabled));

    this.typeChangeSubscription = this.productForm
      .get('type')
      .valueChanges.pipe(startWith(null))
      .subscribe(type => this.toggleType(type));
  }
Example #26
Source File: user.component.ts    From enterprise-ng-2020-workshop with MIT License 6 votes vote down vote up
ngOnInit() {
    this.users$ = this.userService.users$;

    this.userForm = this.fb.group({
      id: '',
      username: ['', [Validators.required, Validators.minLength(5)]],
      name: ['', [Validators.required, Validators.minLength(5)]],
      surname: ['', [Validators.required, Validators.minLength(5)]]
    });

    this.isEdit$ = this.userForm.get('id').valueChanges.pipe(
      startWith(''),
      map((id) => ({ value: (id || '').length > 0 }))
    );
  }
Example #27
Source File: date-filter.component.ts    From zorro-fire-log with MIT License 6 votes vote down vote up
ngOnInit(): void {
    this.toggleControl = new FormControl(this.dateFilter.enabled);
    this.fromDateControl = new FormControl(this.dateFilter.from);
    this.toDateControl = new FormControl(this.dateFilter.to);

    combineLatest(
      this.toggleControl.valueChanges.pipe(startWith(this.toggleControl.value)),
      this.fromDateControl.valueChanges.pipe(
        startWith(this.fromDateControl.value)
      ),
      this.toDateControl.valueChanges.pipe(startWith(this.toDateControl.value))
    )
      .pipe(takeUntil(this.destroy$))
      .subscribe(([enabled, from, to]) =>
        this.dateFilterChange.emit({ enabled, from, to })
      );
  }