rxjs/operators#concatMap TypeScript Examples

The following examples show how to use rxjs/operators#concatMap. 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: index.ts    From dbm with Apache License 2.0 6 votes vote down vote up
stylesheets$ = resolve("**/[!_]*.scss", { cwd: "src" })
  .pipe(
    concatMap(file => zip(
      of(ext(file, ".css")),
      transformStyle({
        from: `src/${file}`,
        to: ext(`${base}/${file}`, ".css")
      }))
    )
  )
Example #2
Source File: scan-announcer.ts    From pantry_party with Apache License 2.0 6 votes vote down vote up
constructor(
    stream: Observable<FinalScanResults>
  ) {
    stream.pipe(
      takeUntil(this.ngUnsubscribe),
      concatMap(r => {
        if (r.status === "failure") {
          return this.speak("Item lookup failure");
        } else {
          return this.speak(r.itemName);
        }
      })
    ).subscribe(
      r => console.log("successfully spoke"),
      e => console.log("error speaking", e.message)
    );
  }
Example #3
Source File: auth.interceptor.ts    From auth0-angular with MIT License 6 votes vote down vote up
/**
   * Duplicate of AuthService.getAccessTokenSilently, but with a slightly different error handling.
   * Only used internally in the interceptor.
   * @param options The options for configuring the token fetch.
   */
  private getAccessTokenSilently(
    options?: GetTokenSilentlyOptions
  ): Observable<string> {
    return of(this.auth0Client).pipe(
      concatMap((client) => client.getTokenSilently(options)),
      tap((token) => this.authState.setAccessToken(token)),
      catchError((error) => {
        this.authState.refresh();
        return throwError(error);
      })
    );
  }
Example #4
Source File: wallet-state-service.ts    From bitcoin-s-ts with MIT License 6 votes vote down vote up
private startPollingTimer(delay: number, time: number) {
    this.stopPollingTimer()
    this.pollingTimer$ = timer(delay, time).pipe(
      tap(_ => { this.state = WalletServiceState.polling }),
      concatMap(() => this.messageService.serverHeartbeat().pipe(
        catchError(e => of({success: false})),
      )),
    ).subscribe(r => {
      // console.debug('polling', r)
      if (r.success === true) {
        this.setOnline()
      } else {
        this.setOffline()
      }
    })
  }
Example #5
Source File: account.service.ts    From angular-10-facebook-login-example with MIT License 6 votes vote down vote up
login() {
        // login with facebook then authenticate with the API to get a JWT auth token
        this.facebookLogin()
            .pipe(concatMap(accessToken => this.apiAuthenticate(accessToken)))
            .subscribe(() => {
                // get return url from query parameters or default to home page
                const returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
                this.router.navigateByUrl(returnUrl);
            });
    }
Example #6
Source File: fetch.ts    From firebase-tools-ui with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an observable view model and query subject. The view model will
 * update when the query emits/changes.
 */
export function createViewModel(
  ref: firebase.database.Reference,
  canDoRealtime$: Observable<boolean>
) {
  const query = new ReplaySubject<QueryParams>(1);
  query.next({ limit: DEFAULT_PAGE_SIZE });
  const viewModel$ = query.pipe(
    switchMap((queryParams) => {
      return canDoRealtime$.pipe(
        concatMap((realtime) =>
          realtime
            ? realtimeToViewModel(ref, queryParams)
            : nonRealtimeToViewModel(ref, queryParams)
        )
      );
    })
  );
  return { query, viewModel$ };
}
Example #7
Source File: request-invitation.page.ts    From fyle-mobile-app with MIT License 6 votes vote down vote up
sendRequestInvitation() {
    from(this.loaderService.showLoader('Sending request to join organization...'))
      .pipe(
        concatMap(() => this.invitationRequestsService.upsertRouter(this.fg.controls.email.value)),
        finalize(async () => {
          await this.loaderService.hideLoader();
        }),
        catchError((err) => {
          if (err.status === 400) {
            this.currentPageState = this.RequestInvitationStates.alreadySent;
          } else {
            this.currentPageState = this.RequestInvitationStates.failure;
          }
          return throwError(err);
        })
      )
      .subscribe(() => {
        this.currentPageState = this.RequestInvitationStates.success;
      });
  }
Example #8
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 #9
Source File: set-role.component.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
// 初始化数据
  initPermission(): void {
    // 通过角色id获取这个角色拥有的权限码
    this.dataService.getPermissionById(this.id).pipe(concatMap((authCodeArr => {
      this.authCodeArr = authCodeArr;
      // 获取所有菜单
      return this.menusService.getMenuList({pageNum: 0, pageSize: 0})
    }))).subscribe(response => {
      // isOpen表示 节点是否展开
      const menuArray: (Menu & { isOpen?: boolean, checked?: boolean })[] = response.list;
      menuArray.forEach(item => {
        item.isOpen = false;
        item.checked = this.authCodeArr.includes(item.code!);
      });
      this.permissionList = fnAddTreeDataGradeAndLeaf(fnFlatDataHasParentToTree(menuArray));
      this.cdr.markForCheck();
    })
  }
Example #10
Source File: debug.ts    From homebridge-esphome-ts with GNU General Public License v3.0 6 votes vote down vote up
writeReadDataToLogFile = (host: string, device: EspDevice): void => {
    const espDevice: unknown = device;
    if (existsSync(join('/tmp')) && isRecord(espDevice) && espDevice.socket instanceof EspSocket) {
        const socket: EspSocket = espDevice.socket;
        const fileName = `esphome-log-${Date.now()}-${host}.json`;
        socket.espData$
            .pipe(
                map(
                    (data: ReadData): Record<string, string | number> => ({
                        type: data.type,
                        payload: Buffer.from(data.payload).toString('base64'),
                        time: Date.now(),
                    }),
                ),
                concatMap(
                    (data: Record<string, string | number>): Observable<void> =>
                        from(fs.appendFile(join('/tmp', fileName), `${JSON.stringify(data)}\n`)),
                ),
            )
            .subscribe();
    }
}
Example #11
Source File: component.ts    From open-source with MIT License 6 votes vote down vote up
export function componentUpdate(opts: Required<Schema>): Observable<any> {
  if (opts.dryRun) {
    logInfo('> Updating component');
    return of(true);
  }
  return readFile(opts.file).pipe(
    concatMap((content) => {
      const file = relative(opts.path, opts.file);
      let source = convertTsInlineTemplate(file, content);
      source = convertTsInlineUrlExtension(file, content);
      return source !== content
        ? writeFile(opts.file, source)
        : throwError(null);
    }),
  );
}
Example #12
Source File: util.ts    From ngrx-issue-tracker with MIT License 6 votes vote down vote up
withLatestFromDeferred = <A, B>(other: Observable<B>) =>
  pipe(concatMap((value: A) => of(value).pipe(withLatestFrom(other))))
Example #13
Source File: app.component.ts    From capture-lite with GNU General Public License v3.0 6 votes vote down vote up
private restoreAppState() {
    this.cameraService.restoreKilledCaptureEvent$
      .pipe(
        concatMap(photo => this.captureService.capture(photo)),
        catchError((err: unknown) => this.errorService.toastError$(err)),
        untilDestroyed(this)
      )
      .subscribe();
  }