How to use the rxjs/operators.mergeMap function in rxjs

To help you get started, we’ve selected a few rxjs examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github dang1412 / ccex-api / src / exchanges / binance / orderbook / binance-orderbook.ts View on Github external
private startOrderbook$(pair: string): Observable {
    const channel = binanceOrderbookChannel(pair);
    const ws = new WebSocketRxJs(channel);
    this.pairSocketMap[pair] = ws;

    // orderbook fetched from rest api
    const fetchOrderbook$ = from(this.fetchOrderbook(pair));
    // orderbook (diff) realtime stream
    const update$ = ws.message$.pipe(map(adaptBinanceWsOrderbook));
    // orderbook (diff) realtime stream, buffered in time range: [fetch start => fetch done]
    const updateBufferBeforeFetchDone$ = update$.pipe(
      buffer(fetchOrderbook$),
      take(1),
      mergeMap((orderbooks) => {
        return from(orderbooks);
      }),
    );

    // start these 2 streams concurrently at first, data come in order and then complete:
    //  - orderbook rest api fetch,
    //  - realtime update orderbooks in time range of [fetch start => fetch done]
    //  - complete
    const initOrderbook$ = merge(fetchOrderbook$, updateBufferBeforeFetchDone$);

    // after init orderbooks come, keep listening to diff orderbook stream and reflect it in current orderbook
    return concat(initOrderbook$, update$).pipe(
      scan((orderbook, update) => {
        if (!orderbook.lastUpdateId || !update.lastUpdateId) {
          return updateOrderbook(orderbook, update);
        }
github new-eden-social / new-eden-social / src / services / comment / comment.service.ts View on Github external
private async sendNotificationToParticipantsAsAlliance(
    senderAllianceId: number,
    commentId: string,
    postId: string,
  ): Promise {
    const eventUuid = uuidv4();
    const participants = await this.getParticipantsForPost(postId);
    await from(participants.characterIds).pipe(
      mergeMap(id => this.notificationClient.service.create({
        eventUuid,
        senderAllianceId,
        recipientId: id,
        commentId,
        postId,
        type: NOTIFICATION_TYPE.NEW_COMMENT_ON_A_POST_YOU_PARTICIPATE,
      }), this.NOTIFICATIONS_PARALLEL_CREATE), // Create notifications in parallel
    ).toPromise();
  }
}
github sourcegraph / sourcegraph / src / search / saved-queries / SavedQueryUpdateForm.tsx View on Github external
function updateSavedQueryFromForm(props: Props, fields: SavedQueryFields): Observable {
    // If the subject changed, we need to create it on the new subject and
    // delete it on the old subject.
    if (props.savedQuery.subject.id !== fields.subject) {
        return createSavedQuery(
            { id: fields.subject },
            fields.description,
            fields.query,
            fields.showOnHomepage,
            fields.notify,
            fields.notifySlack,
            true
        ).pipe(
            mergeMap(() => deleteSavedQuery(props.savedQuery.subject, props.savedQuery.id, true)),
            mergeMap(() => refreshConfiguration().pipe(concat([null])))
        )
    }

    // Otherwise, it's just a simple update.
    return updateSavedQuery(
        props.savedQuery.subject,
        props.savedQuery.id,
        fields.description,
        fields.query,
        fields.showOnHomepage,
        fields.notify,
        fields.notifySlack
    )
}
github lordfriend / Deneb / src / app / home / user-center / user-center.service.ts View on Github external
addWebHookToken(querystring: string): Observable {
        const params = new URLSearchParams(querystring);
        const token_id = params.get('token_id');
        const web_hook_id = params.get('web_hook_id');
        if (token_id && web_hook_id) {
            return this._http.get(`/api/web-hook/${web_hook_id}`).pipe(
                map(res => {
                    let result = res.json().data as any;
                    result.permissions = JSON.parse(result.permissions);
                    return result as WebHook;
                }),
                catchError(this.handleError),
                mergeMap((webHook: WebHook) => {
                    let permissionInfo = '<div>该WebHook将会需要以下权限</div><ul>' + webHook.permissions.map((permission_key) =&gt; {
                        return `<li>${PERMISSION_INFO[permission_key]}</li>`;
                    }).join('') + '</ul>';
                    let content = `<div>将要添加此Web Hook ${webHook.name}。您可以随时删除该Web Hook。</div>`;
                    if (webHook.permissions &amp;&amp; webHook.permissions.length &gt; 0) {
                        content += permissionInfo;
                    }
                    console.log(content);
                    const dialogRef = this._dialogService.open(ConfirmDialogModal, {
                        stickyDialog: true,
                        backdrop: true
                    });
                    dialogRef.componentInstance.title = '确定添加Web Hook吗?';
                    dialogRef.componentInstance.content = content;

                    return dialogRef.afterClosed().pipe(
github ffxiv-teamcraft / ffxiv-teamcraft / src / app / pages / profile / profile / profile.component.ts View on Github external
map(sets => sets.map(set => {
                                const job = ProfileComponent.craftingJobs[set.jobId - 8];
                                if (job !== undefined) {
                                    set.abbr = job.abbr;
                                    set.name = job.name;
                                    return set;
                                }
                            }).filter(row => row !== null)
                        )
                    )
                )
            ).subscribe(jobs => this.jobs = jobs));
        this.subscriptions.push(
            userService.getUserData()
                .pipe(
                    mergeMap(user => {
                        return combineLatest(
                            user.contacts.map(contactId => {
                                return this.userService.getCharacter(contactId)
                                    .pipe(
                                        map(details => {
                                            details.$key = contactId;
                                            return details;
                                        }),
                                        catchError(() => {
                                            return of(null);
                                        })
                                    );
                            })
                        ).pipe(map(res => res.filter(row => row !== null)));
                    })
                ).subscribe(res => this.contacts = res));
github HaithemMosbahi / book-store / src / app / core / effects / core.effects.ts View on Github external
import { Actions, Effect, ofType } from '@ngrx/effects';

import { of } from 'rxjs';
import { map, mergeMap } from 'rxjs/operators';
import { CartService } from './../services/cart.service';

import * as coreActions from './../actions/core.actions';

@Injectable()
export class CoreEffects {
  constructor(private actions$: Actions, private cartService: CartService) {}

  @Effect()
  loadCart = this.actions$.pipe(
    ofType(coreActions.LOAD_CART_CONTENT),
    mergeMap(() => {
      const result = {
        count: this.cartService.count(),
        total: this.cartService.total()
      };
      return of(result);
    }),
    map(result => new coreActions.LoadCartContentSuccess(result))
  );
}
github vmware-samples / vmware-blockchain-samples / supply-chain / src / app / core / blockchain / blockchain.service.ts View on Github external
callWithPromise(methodName: string, ...args: any[]): Promise {
    return fromPromise(this.servicePromise).pipe(mergeMap(() =&gt; {
      return new Promise((resolve, reject) =&gt; {
        if (args.length === 0) {
          return this.ordersContract[methodName](this.callbackToResolve(resolve, reject));
        } else {
          return this.ordersContract[methodName](...args, this.callbackToResolve(resolve, reject));
        }
      });
    })).toPromise();
  }
github Lumeer / web-ui / src / app / core / store / link-instances / link-instances.effects.ts View on Github external
mergeMap(action => {
      const {linkInstance, originalLinkInstance} = action.payload;
      const {linkTypeId, id: linkInstanceId} = linkInstance;
      return this.store$.pipe(
        select(selectLinkTypeById(linkTypeId)),
        take(1),
        mergeMap(linkType =>
          hasFilesAttributeChanged(linkType, linkInstance, originalLinkInstance)
            ? [new FileAttachmentsAction.Get({linkTypeId, linkInstanceId})]
            : []
        )
      );
    })
  );
github mattlewis92 / angular-draggable-droppable / projects / angular-draggable-droppable / src / lib / draggable.directive.ts View on Github external
clone.parentElement!.removeChild(clone);
              this.ghostElement = null;
              this.renderer.setStyle(
                this.element.nativeElement,
                'visibility',
                ''
              );
            });
          }

          this.draggableHelper.currentDrag.next(currentDrag$);
        });

        dragEnded$
          .pipe(
            mergeMap(dragEndData => {
              const dragEndData$ = cancelDrag$.pipe(
                count(),
                take(1),
                map(calledCount => ({
                  ...dragEndData,
                  dragCancelled: calledCount > 0
                }))
              );
              cancelDrag$.complete();
              return dragEndData$;
            })
          )
          .subscribe(({ x, y, dragCancelled }) => {
            this.scroller.destroy();
            this.zone.run(() => {
              this.dragEnd.next({ x, y, dragCancelled });
github SAP / cloud-commerce-spartacus-storefront / projects / core / src / checkout / store / effects / address-verification.effect.ts View on Github external
import { Actions, Effect, ofType } from '@ngrx/effects';
import { Observable, of } from 'rxjs';
import { catchError, map, mergeMap } from 'rxjs/operators';
import { UserAddressConnector } from '../../../user/connectors/address/user-address.connector';
import { makeErrorSerializable } from '../../../util/serialization-utils';
import { CheckoutActions } from '../actions/index';

@Injectable()
export class AddressVerificationEffect {
  @Effect()
  verifyAddress$: Observable&lt;
    CheckoutActions.VerifyAddressSuccess | CheckoutActions.VerifyAddressFail
  &gt; = this.actions$.pipe(
    ofType(CheckoutActions.VERIFY_ADDRESS),
    map(action =&gt; action.payload),
    mergeMap(payload =&gt;
      this.userAddressConnector.verify(payload.userId, payload.address).pipe(
        map(data =&gt; new CheckoutActions.VerifyAddressSuccess(data)),
        catchError(error =&gt;
          of(
            new CheckoutActions.VerifyAddressFail(makeErrorSerializable(error))
          )
        )
      )
    )
  );

  constructor(
    private actions$: Actions,
    private userAddressConnector: UserAddressConnector
  ) {}
}