rxjs/operators#mergeMap TypeScript Examples

The following examples show how to use rxjs/operators#mergeMap. 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
newsletterSignupEpic: EpicSignature = (action$, state$, deps) => {
  return action$.pipe(
    filter(isActionOf(Actions.newsletterSignup)),
    pluck("payload"),
    delay(1000),
    mergeMap(async email => {
      const { tString } = i18nSelector(state$.value);

      try {
        // Validate email
        if (!validateEmailAddress(email)) {
          throw new Error("Invalid email");
        }

        await signupNewsletter(email);

        Toast.success(
          tString(
            "Successfully signed up for the Chorus One newsletter. Please check your email for details.",
          ),
        );
        return Actions.newsletterSignupSuccess();
      } catch (err) {
        Toast.warn(
          tString(
            "Could not register your email. Is your email address typed correctly?",
          ),
        );
        return Actions.newsletterSignupFailure();
      }
    }),
  );
}
Example #3
Source File: websocket-client.ts    From closer-sdk.js with MIT License 6 votes vote down vote up
/**
   * Cold observable
   * @param command Message
   */
  public ask(command: roomCommand.SendMessage | roomCommand.SendCustomMessage): Observable<chatEvents.Received> {
    const ref = this.uuidGenerator.next();
    const newCommand = { ...command, ref };

    return merge(
      of(newCommand).pipe(
        tap((cmd: typeof newCommand) => this.send(cmd)),
        ignoreElements(),
      ),
      this.connection$.pipe(
        filter(chatEvents.Received.isReceived),
        filter(rec => rec.ref === ref),
      ),
      this.connection$.pipe(
        filter(errorEvents.Error.isError),
        filter(rec => rec.ref === ref),
        mergeMap(err => throwError(err, undefined)),
      ),
    ).pipe(
      timeout(this.askTimeoutMs),
      take(1),
    );
  }
Example #4
Source File: wallets-assets.service.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
// DEPRECATED
  requestAssetDataSubscription: Subscription = merge(this.requestAssetData$, this.shouldRequestAssetInformation$)
    .pipe(mergeMap(params => {
      this.walletsAssetsStore.upsert(params._id, { lastTimeUpdated: new Date() });
      return this.getAssetExtraRecord(params)
        .pipe(switchMap(_ => {
          return this.getAssetFullRecord(params)
            .pipe(catchError(error => {
              console.error(error);
              return of(error);
            }));
        }))
        .pipe(catchError(error => {
          console.error(error);
          return of(error);
        }));
    }, 1))
    .subscribe();
Example #5
Source File: bridge-api.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Makes POST request for notify bridge bot.
   * @param bridgeTrade Trade data object.
   * @param transactionHash Hash of transaction.
   * @param walletAddress User's wallet address.
   */
  public notifyBridgeBot(
    bridgeTrade: BridgeTrade,
    transactionHash: string,
    walletAddress: string
  ): Promise<void> {
    return this.getTokenPrice(bridgeTrade.token)
      .pipe(
        mergeMap(price => {
          const body: BridgeBotRequest = {
            txHash: transactionHash,
            walletAddress,
            amount: bridgeTrade.amount.toNumber(),
            fromBlockchain: bridgeTrade.fromBlockchain,
            toBlockchain: bridgeTrade.toBlockchain,
            symbol: bridgeTrade.token.symbol,
            price
          };
          return this.httpService.post(BOT_URL.BRIDGES, body).pipe(switchMap(() => EMPTY));
        })
      )
      .toPromise();
  }
Example #6
Source File: index.ts    From dbm with Apache License 2.0 6 votes vote down vote up
/**
 * Copy all files matching the given pattern
 *
 * Note that this function rebases all files that match the pattern to the
 * target folder, even if the pattern resolves to a parent folder.
 *
 * @param pattern - Pattern
 * @param options - Options
 *
 * @returns File observable
 */
export function copyAll(
  pattern: string, options: CopyOptions
): Observable<string> {
  return resolve(pattern, { ...options, cwd: options.from })
    .pipe(
      mergeMap(file => copy({
        ...options,
        from: `${options.from}/${file}`,
        to:   `${options.to}/${file.replace(/(\.{2}\/)+/, "")}`
      }), 16)
    )
}
Example #7
Source File: pages.service.ts    From FireAdmin with MIT License 6 votes vote down vote up
private pipePages(pagesObservable: Observable<Page[]>) {
    return pagesObservable.pipe(mergeMap(async (pages: Page[]) => {
      const activeSupportedLanguages = this.settings.getActiveSupportedLanguages().map((lang: Language) => lang.key);
      //pages.forEach((page: Page) => { // forEach loop doesn't seems to work well with async/await
      for (let page of pages) {
        // console.log(page);
        page.translations = page.translationId ? await this.getTranslations(page.translationId).pipe(take(1)).toPromise() : {};
        // console.log(page.translations);
        const pageLanguages = Object.keys(page.translations);
        page.author = page.createdBy ? this.users.getFullName(page.createdBy) : of(null);
        page.isTranslatable = !activeSupportedLanguages.every((lang: string) => pageLanguages.includes(lang));
      }
      //});
      return pages;
    }));
  }
Example #8
Source File: fake-backend.service.ts    From ng-conf-2020-workshop with MIT License 6 votes vote down vote up
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        this.users = JSON.parse(this.localStorage.getItem('users')) || [];
        return of(null).pipe(mergeMap(() => {
            // login user
            if (request.url.endsWith('/login') && request.method === 'POST') {
                return this.loginHandle(request);
            }

            // register user
            if (request.url.endsWith('/register') && request.method === 'POST') {
                const user = this.getStorageUser(request);
                return this.registerHandle(user);
            }

            // login user with external provider
            if (request.url.endsWith('/extlogin') && request.method === 'POST') {
                const user = this.getStorageExtUser(request);
                return this.registerHandle(user, true);
            }

            // Microsoft-specific OIDC discovery URI
            if (request.url.endsWith('ms-discovery/keys') && request.method === 'GET') {
                return of(new HttpResponse({ status: 200, body: msKeys }));
            }

            return next.handle(request);
        }))
        .pipe(materialize())
        .pipe(dematerialize());
    }
Example #9
Source File: add-photo.component.ts    From mylog14 with GNU General Public License v3.0 6 votes vote down vote up
private saveRecordWithLoading(): Observable<any> {
    return forkJoin([
      this.loadingService.showLoading('description.addingDataAndVerifiableInformation', 10000),
      this.dataStore.pushRecord(this.record.getValue())
    ])
      .pipe(
        mergeMap(([loading, _]) => loading.dismiss()),
      );
  }
Example #10
Source File: app.effects.ts    From Angular-Cookbook with MIT License 6 votes vote down vote up
getUsers$ = createEffect(() =>
    this.actions$.pipe(
      ofType(APP_ACTIONS.GET_USERS),
      mergeMap(() => this.userService.getUsers()
        .pipe(
          map(users => {
            return getUsersSuccess({
              users
            })
          }),
          catchError((error) => of(getUsersFailure({
            error
          })))
        )
      )
    )
  );
Example #11
Source File: product-quick-create.component.ts    From pantry_party with Apache License 2.0 6 votes vote down vote up
saveProduct() {
    this.goToStep("saving");

    this.createParentProduct().pipe(
      tap(_ => this.saveStatus = "Creating Product"),
        mergeMap(_ => this.createNewProduct()),
        tap(p => this.updateScannedItem(p, this.product.location)),
      tap(_ => this.saveStatus = "Done"),
      catchError((e: Error | HttpErrorResponse) => {
        let errMsg = `There was an error saving the product: ${e.message}`;

        if (e instanceof HttpErrorResponse) {
          errMsg += JSON.stringify(e.error);
        }

        this.saveStatus = errMsg;
        throw e;
      })
    ).subscribe(_ => {
      this.saveStatus = "Product Created";
      setTimeout(() => {
        this.nextScannedItem();
        this.goToStep("name");
      }, 500);
    });

  }
Example #12
Source File: ɵmanifest-registry.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
private installCapabilitiesLookupRequestHandler(): void {
    Beans.get(MessageClient).observe$<ManifestObjectFilter>(ManifestRegistryTopics.LookupCapabilities)
      .pipe(takeUntil(this._destroy$))
      .subscribe((request: TopicMessage<ManifestObjectFilter>) => runSafe(() => {
        const replyTo = request.headers.get(MessageHeaders.ReplyTo);
        const appSymbolicName = request.headers.get(MessageHeaders.AppSymbolicName);
        const lookupFilter = request.body || {};

        // The queried capabilities may change on both, capability or intention change, because the computation
        // of visible and qualified capabilities depends on registered capabilities and manifested intentions.
        const registryChange$ = merge(this._capabilityStore.change$, this._intentionStore.change$);
        const finder$ = defer(() => of(this._capabilityStore.find(lookupFilter)));
        return finder$
          .pipe(
            expand(() => registryChange$.pipe(take(1), mergeMap(() => finder$))),
            filterArray(capability => this.isApplicationQualifiedForCapability(appSymbolicName, capability)),
            distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b)),
            takeUntilUnsubscribe(replyTo),
          )
          .subscribe(capabilities => { // eslint-disable-line rxjs/no-nested-subscribe
            Beans.get(MessageClient).publish<Capability[]>(replyTo, capabilities, {headers: new Map().set(MessageHeaders.Status, ResponseStatusCodes.OK)});
          });
      }));
  }
Example #13
Source File: emote.component.ts    From App with MIT License 6 votes vote down vote up
interactError = new Subject<string>().pipe(
		mergeMap(x => scheduled([
			of(!!x ? 'ERROR: ' + x : ''),
			timer(5000).pipe(
				takeUntil(this.interactError),
				mapTo('')
			)
		], asyncScheduler).pipe(mergeAll()))
	) as Subject<string>;
Example #14
Source File: fetch-translations.ts    From react-starter-boilerplate with MIT License 6 votes vote down vote up
fromBabelsheet({
  spreadsheetId: babelsheetConfig.spreadsheetId,
  credentials: require(path.join(projectRoot, babelsheetConfig.credentials)),
}).pipe(
  groupBy(
    ({ language }) => language,
    { element: ({ path, ...entry }) => ({ ...entry, path: path.join(".") }) }
  ),
  mergeMap(languageEntries$ => languageEntries$.pipe(
    writeJSONFile(`./src/i18n/data/${languageEntries$.key}.json`)
  )),
).subscribe(
  ({ filePath, entryCount }) => {
    console.log(`Wrote file: "${filePath}" with ${entryCount} entries`);
  }
);
Example #15
Source File: collection.effects.ts    From router with MIT License 6 votes vote down vote up
addBookToCollection$ = createEffect(() =>
    this.actions$.pipe(
      ofType(SelectedBookPageActions.addBook),
      mergeMap(({ book }) =>
        this.storageService.addToCollection([book]).pipe(
          map(() => CollectionApiActions.addBookSuccess({ book })),
          catchError(() => of(CollectionApiActions.addBookFailure({ book })))
        )
      )
    )
  );
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: title.service.ts    From blockcore-hub with MIT License 6 votes vote down vote up
initialize() {
        this.router.events.pipe(
            filter(event => event instanceof NavigationEnd),
            map(() => this.router.routerState.root),
            map(route => {
                while (route.firstChild) {
                    route = route.firstChild;
                }
                return route;
            }),
            filter(route => route.outlet === 'primary'),
            mergeMap(route => route.data),
            // eslint-disable-next-line @typescript-eslint/dot-notation
            map(data => ({ title: data['title'], prefix: data['prefix'] })),
        ).subscribe(title => {

            let formattedTitle = title.title != null ? title.title : '';

            if (title.prefix != null) {
                formattedTitle = title.prefix + ' - ' + formattedTitle;
            }

            // For the document title, we'll append the app title.
            // if (this.appTitle != null) {
            // this.document.title = formattedTitle + ' - ' + this.appTitle;
            this.document.title = this.setup.name + ' - ' + formattedTitle;
            // }

            this.title.next(formattedTitle);
        });
    }
Example #18
Source File: rest-api-connector.service.ts    From attack-workbench-frontend with Apache License 2.0 6 votes vote down vote up
/**
     * Get all objects related to a data source
     * @param id the STIX ID of the data source
     * @returns list of data components related to the data source along with the data components' relationships with techniques
     */
    public getAllRelatedToDataSource(id: string): Observable<StixObject[]> {
        let dataComponents$ = this.getAllDataComponents();
        return dataComponents$.pipe(
            map(result => { // get related data component objects
                let dataComponents = result.data as DataComponent[];
                return dataComponents.filter(d => d.data_source_ref == id);
            }),
            mergeMap(dataComponents => { // get relationships for each data component
                let relatedTo = dataComponents.map(dc => this.getRelatedTo({sourceOrTargetRef: dc.stixID}));
                if (!relatedTo.length) return of(dataComponents);
                return forkJoin(relatedTo).pipe(
                    map(relationships => {
                        let all_results: StixObject[] = [];
                        for(let relationship_result of relationships) {
                            all_results = all_results.concat(relationship_result.data)
                        }
                        return all_results.concat(dataComponents);
                    })
                );
            }),
            catchError(this.handleError_continue([])),
            share()
        );
    }
Example #19
Source File: member.effects.ts    From dating-client with MIT License 6 votes vote down vote up
LoadMember$ = createEffect(() => this.actions$.pipe(
    ofType(MemberActions.loadMember),
    mergeMap(({ id }) => {
      return this.memberService.getMemberDetails(id).pipe(
        map(user => MembersApiActions.loadMemberSuccess({ user })),
        catchError(error => of(MembersApiActions.loadMemberFailure({ error, id }))),
      );
    })
  ));
Example #20
Source File: title.service.ts    From EXOS-Core with MIT License 6 votes vote down vote up
initialize() {
        this.router.events.pipe(
            filter(event => event instanceof NavigationEnd),
            map(() => this.router.routerState.root),
            map(route => {
                while (route.firstChild) {
                    route = route.firstChild;
                }
                return route;
            }),
            filter(route => route.outlet === 'primary'),
            mergeMap(route => route.data),
            // tslint:disable-next-line: no-string-literal
            map(data => ({ title: data['title'], prefix: data['prefix'] })),
        ).subscribe(title => {

            let formattedTitle = title.title != null ? title.title : '';

            if (title.prefix != null) {
                formattedTitle = title.prefix + ' - ' + formattedTitle;
            }

            // For the document title, we'll append the app title.
            if (this.appTitle != null) {
                // this.document.title = formattedTitle + ' - ' + this.appTitle;
                this.document.title = this.appTitle + ' - ' + formattedTitle;
            }

            this.title.next(formattedTitle);
        });
    }
Example #21
Source File: merge-expenses.service.ts    From fyle-mobile-app with MIT License 6 votes vote down vote up
generateProjectOptions(expenses: Expense[]): Observable<OptionsData> {
    return from(expenses).pipe(
      filter((expense) => expense.tx_project_id),
      map((expense) => ({
        label: expense.tx_project_id,
        value: expense.tx_project_id,
      })),
      mergeMap((option) => this.formatProjectOptions(option)),
      reduce((acc, curr) => {
        acc.push(curr);
        return acc;
      }, []),
      map((options: Option[]) => this.formatOptions(options))
    );
  }
Example #22
Source File: analysis-progress.page.ts    From geonetwork-ui with GNU General Public License v2.0 6 votes vote down vote up
ngOnInit(): void {
    this.subscription = new Subscription()
    this.statusFetch$ = this.activatedRoute.params.pipe(
      mergeMap(({ id }) =>
        interval(500).pipe(
          switchMap(() => this.fileUploadApiService.findUploadJob(id)),
          tap((job: UploadJobStatusApiModel) => this.facade.setUpload(job)),
          tap((job: UploadJobStatusApiModel) => (this.progress = job.progress)),
          filter(
            (job: UploadJobStatusApiModel) =>
              ![Pending, Analyzing].includes(job.status)
          ),
          take(1)
        )
      )
    )

    this.subscription.add(
      this.statusFetch$.subscribe((job: UploadJobStatusApiModel) =>
        this.onJobFinish(job)
      )
    )
  }
Example #23
Source File: add.ts    From ble with Apache License 2.0 6 votes vote down vote up
addVertexOrEntity: Epic = (action$, { store }) => {
	return action$.pipe(
		// we listen specifically on the background because when a user clicks another object they
		// probably expect to select it
		ofType('backgroundPointerDown'),
		pluck('ev', 'data'),
		filter((data) => data.button === 0 || data.pointerType === 'touch'),
		map(({ global }) => store.editor.screenToWorld({
			x: global.x,
			y: global.y,
		})),
		map((posInWorld) => snapToGrid(posInWorld, store.editor.gridCellSize)),
		filter(() => store.editor.mode === EditorMode.addVertex || store.editor.mode === EditorMode.addBlock),
		mergeMap((posInWorld: IPoint) => {
			switch (store.editor.mode) {
				case EditorMode.addVertex:
					return of({
						type: 'addVertex',
						pos: posInWorld,
					});
				case EditorMode.addBlock:
					return of({
						type: 'createEntity',
						pos: posInWorld,
					});
			}

			return empty();
		}),
	);
}
Example #24
Source File: auth.service.ts    From nestjs-rest-sample with GNU General Public License v3.0 6 votes vote down vote up
validateUser(username: string, pass: string): Observable<UserPrincipal> {
    return this.userService.findByUsername(username).pipe(
      //if user is not found, convert it into an EMPTY.
      mergeMap((p) => (p ? of(p) : EMPTY)),

      // Using a general message in the authentication progress is more reasonable.
      // Concise info could be considered for security.
      // Detailed info will be helpful for crackers.
      // throwIfEmpty(() => new NotFoundException(`username:${username} was not found`)),
      throwIfEmpty(() => new UnauthorizedException(`username or password is not matched`)),

      mergeMap((user) => {
        const { _id, password, username, email, roles } = user;
        return user.comparePassword(pass).pipe(map(m => {
          if (m) {
            return { id: _id, username, email, roles } as UserPrincipal;
          }else {
            // The same reason above.
            //throw new UnauthorizedException('password was not matched.')
            throw new UnauthorizedException('username or password is not matched')
          }
        }))
      })
    );
  }
Example #25
Source File: rxjs-tree.ts    From open-source with MIT License 6 votes vote down vote up
/**
 * Similar to @angular-devkit's Tree.visit.
 */

export function treeVisit(path: string): Observable<string> {
  return stat(path).pipe(
    mergeMap((stats) => {
      if (stats.isDirectory()) {
        return readDir(path).pipe(
          mergeMap(files => from(files)),
          mergeMap(file => treeVisit(join(path, file))),
        );
      } else if (stats.isFile()) {
        return of(path);
      }
      return throwError(`Not a directory nor file: ${path}`);
    }),
  );
}
Example #26
Source File: app.effects.ts    From wingsearch with GNU General Public License v3.0 6 votes vote down vote up
loadLanguage$ = createEffect(() => this.actions$.pipe(
        ofType(ROOT_EFFECTS_INIT, changeLanguage),
        mergeMap((action) => {
            const language = action.language || (this.cookies.hasConsent() && this.cookies.getCookie('language'))
            if (language)
                return from(this.http.get(this.I18N_FOLDER + language + '.json')).pipe(
                    map((data) => ({ type: '[App] Set language', payload: data, language }))
                )
            else
                return of({ type: '[App] English' })
        })
    ))
Example #27
Source File: dia-backend-asset-uploading.service.ts    From capture-lite with GNU General Public License v3.0 6 votes vote down vote up
private uploadProof$(proof: Proof) {
    const scalingDuration = 1000;
    const attempBase = 2;
    return this.diaBackendAssetRepository.addCapture$(proof).pipe(
      first(),
      catchError((err: unknown) => {
        if (
          err instanceof HttpErrorResponse &&
          err.error.error.type === 'duplicate_asset_not_allowed'
        ) {
          return this.diaBackendAssetRepository.fetchByProof$(proof);
        }
        return throwError(err);
      }),
      map(diaBackendAsset => {
        proof.diaBackendAssetId = diaBackendAsset.id;
        return proof;
      }),
      retryWhen(err$ =>
        err$.pipe(
          mergeMap((_, attempt) => {
            return timer(attempBase ** attempt * scalingDuration);
          })
        )
      )
    );
  }
Example #28
Source File: chat-drawer.component.ts    From onchat-web with Apache License 2.0 6 votes vote down vote up
@Debounce(300)
  rtc() {
    let mediaStream: MediaStream;
    this.overlay.loading();

    this.mediaDevice.getUserMedia({ video: true, audio: { echoCancellation: true } }).pipe(
      tap(stream => {
        mediaStream = stream;
        this.peer.call(this.globalData.chatroomId);
      }),
      mergeMap(() => this.socket.on<Result<[requester: User, target: User]>>(SocketEvent.RtcCall)),
      take(1),
      success(),
      filter(({ data: [requester] }) => this.globalData.user.id === requester.id),
    ).subscribe(({ data: [_, target] }) => {
      this.overlay.modal({
        component: RtcComponent,
        componentProps: {
          target,
          mediaStream,
          isRequester: true,
        }
      });

      this.overlay.dismissLoading();
    });
  }
Example #29
Source File: LiquidityPoolTask.ts    From guardian with Apache License 2.0 6 votes vote down vote up
getPoolCurrencyOptions =
  (apiRx: ApiRx, tokens: Record<string, number>) =>
  (poolId: string, currencyId: string | string[] | 'fTokens' | 'all') => {
    let currencyIds: string[] = [];
    switch (currencyId) {
      case 'all':
        currencyIds = Object.keys(tokens);
        break;
      case 'fTokens':
        currencyIds = Object.keys(tokens).filter((key) => key.startsWith('f'));
        break;
      default:
        currencyIds = typeof currencyId === 'string' ? [currencyId] : currencyId;
        break;
    }
    return of(currencyIds).pipe(
      mergeMap((x) => x),
      mergeMap((currency) =>
        combineLatest([of(currency), apiRx.query.syntheticLiquidityPools.poolCurrencyOptions(poolId, currency)])
      )
    );
  }