當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript rxjs.merge函數代碼示例

本文整理匯總了TypeScript中rxjs.merge函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript merge函數的具體用法?TypeScript merge怎麽用?TypeScript merge使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了merge函數的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: useAllStreams

 protected useAllStreams(
   wc: IStream<OutWcMessage, InWcMsg> & WebChannel,
   sig: IStream<OutSigMsg, InSigMsg>
 ): IAllStreams<OutMsg, InMsg> {
   const wcStream = this.useWebChannelStream(wc)
   const sigStream = this.useSignalingStream(sig)
   return {
     message: merge(
       wcStream.message.pipe(
         map(({ senderId, recipientId, msg }) => ({
           streamId: wcStream.id,
           senderId,
           recipientId,
           msg,
         }))
       ),
       sigStream.message.pipe(
         map(({ senderId, recipientId, msg }) => ({
           streamId: sigStream.id,
           senderId,
           recipientId,
           msg,
         }))
       )
     ),
     sendOver: (
       streamId: number,
       msg: Uint8Array | OutMsg,
       recipientId: number,
       senderId: number
     ) => {
       if (streamId === wcStream.id) {
         wcStream.send(msg, recipientId)
       } else {
         sigStream.send(msg, recipientId, senderId)
       }
     },
   }
 }
開發者ID:openpaas-ng,項目名稱:netflux,代碼行數:39,代碼來源:Service.ts

示例2: mergeMap

        mergeMap(data => {
          const session = uuid();
          const kernel = Object.assign({}, data.response, {
            channel: kernels.connect(
              config,
              data.response.id,
              session
            )
          });

          kernel.channel.next(kernelInfoRequest());

          return merge(
            of(
              actions.activateKernelFulfilled({
                serverId,
                kernelName,
                kernel
              })
            )
          );
        })
開發者ID:nteract,項目名稱:play,代碼行數:22,代碼來源:epics.ts

示例3: ngOnInit

  ngOnInit() {
    // Setup logger
    if (environment.production) {
      Logger.enableProductionMode();
    }

    log.debug('init');

    // Setup translations
    this.i18nService.init(
      environment.defaultLanguage,
      environment.supportedLanguages
    );

    const onNavigationEnd = this.router.events.pipe(
      filter(event => event instanceof NavigationEnd)
    );

    // Change page title on navigation or language change, based on route data
    merge(this.translateService.onLangChange, onNavigationEnd)
      .pipe(
        map(() => {
          let route = this.activatedRoute;
          while (route.firstChild) {
            route = route.firstChild;
          }
          return route;
        }),
        filter(route => route.outlet === 'primary'),
        mergeMap(route => route.data)
      )
      .subscribe(event => {
        const title = event['title'];
        if (title) {
          this.titleService.setTitle(this.translateService.instant(title));
        }
      });
  }
開發者ID:epot,項目名稱:Gifter,代碼行數:38,代碼來源:app.component.ts

示例4: fetchNodesNetwork

export function fetchNodesNetwork(): Observable<
  RequestResponse<NodesNetworkResponse>
> {
  const [success, error] = partition(
    (response: RequestResponse<NodesNetworkResponse>) => response.code < 300
  )(request<NodeNetworkResponse[]>("/net/v1/nodes").pipe(share()));

  return merge(
    success,
    error.pipe(
      tap((response: RequestResponse<NodesNetworkResponse>) => {
        const responseMessage =
          response.response && typeof response.response === "object"
            ? JSON.stringify(response.response)
            : response.response;
        throw new Error(
          `Network Nodes API request failed: ${response.code} ${
            response.message
          }:${responseMessage}`
        );
      })
    )
  );
}
開發者ID:dcos,項目名稱:dcos-ui,代碼行數:24,代碼來源:NodesNetworkClient.ts

示例5: runTargetSpec

export function runTargetSpec(
  host: TestProjectHost,
  targetSpec: TargetSpecifier,
  overrides = {},
  timeout = DefaultTimeout,
  logger: logging.Logger = new logging.NullLogger(),
): Observable<BuildEvent> {
  targetSpec = { ...targetSpec, overrides };
  const workspaceFile = normalize('angular.json');
  const workspace = new experimental.workspace.Workspace(host.root(), host);

  // Emit when runArchitect$ completes or errors.
  // TODO: There must be a better way of doing this...
  let finalizeCB = () => { };
  const runArchitectFinalize$ = new Observable(obs => {
    finalizeCB = () => obs.next();
  });

  // Load the workspace from the root of the host, then run a target.
  const runArchitect$ = workspace.loadWorkspaceFromHost(workspaceFile).pipe(
    concatMap(ws => new Architect(ws).loadArchitect()),
    concatMap(arch => arch.run(arch.getBuilderConfiguration(targetSpec), { logger })),
    finalize(() => finalizeCB()),
  );

  // Error out after the timeout if runArchitect$ hasn't finalized.
  const timeout$ = timer(timeout).pipe(
    takeUntil(runArchitectFinalize$),
    concatMapTo(throwError(`runTargetSpec timeout (${timeout}) reached.`)),
  );

  return merge(
    timeout$,
    runArchitect$,
  );
}
開發者ID:baconwaffles,項目名稱:angular-cli,代碼行數:36,代碼來源:run-target-spec.ts

示例6: mergeMap

        mergeMap((tick) => {
          const qSourceBuffer = createOrReuseQueuedSourceBuffer(
            sourceBuffersManager, bufferType, adaptation, options);
          const strategy = getAdaptationSwitchStrategy(
            qSourceBuffer.getBuffered(), period, bufferType, tick);

          if (strategy.type === "needs-reload") {
            return observableOf(EVENTS.needsMediaSourceReload());
          }

          const cleanBuffer$ = strategy.type === "clean-buffer" ?
            observableConcat(
              ...strategy.value.map(({ start, end }) =>
                qSourceBuffer.removeBuffer(start, end)
              )).pipe(ignoreElements()) : EMPTY;

          const bufferGarbageCollector$ = garbageCollectors.get(qSourceBuffer);
          const adaptationBuffer$ = createAdaptationBuffer(adaptation, qSourceBuffer);

          return observableConcat(
            cleanBuffer$,
            observableMerge(adaptationBuffer$, bufferGarbageCollector$)
          );
        }));
開發者ID:canalplus,項目名稱:rx-player,代碼行數:24,代碼來源:period_buffer.ts

示例7: manageEveryBuffers

  /**
   * Manage creation and removal of Buffers for every Periods.
   *
   * Works by creating consecutive buffers through the
   * manageConsecutivePeriodBuffers function, and restarting it when the clock
   * goes out of the bounds of these buffers.
   * @param {string} bufferType - e.g. "audio" or "video"
   * @param {Period} basePeriod - Initial Period downloaded.
   * @returns {Observable}
   */
  function manageEveryBuffers(
    bufferType : IBufferType,
    basePeriod : Period
  ) : Observable<IMultiplePeriodBuffersEvent> {
    // Each Period for which there is currently a Buffer, chronologically
    const periodList = new SortedList<Period>((a, b) => a.start - b.start);
    const destroyBuffers$ = new Subject<void>();
    let hasLoadedABuffer = false; // true after the first PeriodBuffer is ready

    /**
     * @param {Object} period
     * @returns {Observable}
     */
    function launchConsecutiveBuffersForPeriod(
      period : Period
    ) : Observable<IMultiplePeriodBuffersEvent> {
      return manageConsecutivePeriodBuffers(bufferType, period, destroyBuffers$).pipe(
        tap((message) => {
          if (message.type === "periodBufferReady") {
            if (!hasLoadedABuffer) {
              hasLoadedABuffer = true;
            }
            periodList.add(message.value.period);
          } else if (message.type === "periodBufferCleared") {
            periodList.removeElement(message.value.period);
          }
        }),
        share()
      );
    }

    /**
     * Returns true if the given time is either:
     *   - less than the start of the chronologically first Period
     *   - more than the end of the chronologically last Period
     * @param {number} time
     * @returns {boolean}
     */
    function isOutOfPeriodList(time : number) : boolean {
      const head = periodList.head();
      const last = periodList.last();
      if (head == null || last == null) { // if no period
        return true;
      }
      return head.start > time || (last.end || Infinity) < time;
    }

    // Restart the current buffer when the wanted time is in another period
    // than the ones already considered
    const restartBuffersWhenOutOfBounds$ = clock$.pipe(
      filter(({ currentTime, wantedTimeOffset }) => {
        return hasLoadedABuffer &&
          !!manifest.getPeriodForTime(wantedTimeOffset + currentTime) &&
          isOutOfPeriodList(wantedTimeOffset + currentTime);
      }),
      tap(({ currentTime, wantedTimeOffset }) => {
        log.info("Buffer: Current position out of the bounds of the active periods," +
          "re-creating buffers.", bufferType, currentTime + wantedTimeOffset);
        hasLoadedABuffer = false;
        destroyBuffers$.next();
      }),
      mergeMap(({ currentTime, wantedTimeOffset }) => {
        const newInitialPeriod = manifest
          .getPeriodForTime(currentTime + wantedTimeOffset);
        if (newInitialPeriod == null) {
          throw new MediaError("MEDIA_TIME_NOT_FOUND",
            "The wanted position is not found in the Manifest.", true);
        }
        return launchConsecutiveBuffersForPeriod(newInitialPeriod);
      })
    );

    return observableMerge(
      launchConsecutiveBuffersForPeriod(basePeriod),
      restartBuffersWhenOutOfBounds$
    );
  }
開發者ID:canalplus,項目名稱:rx-player,代碼行數:87,代碼來源:buffer_orchestrator.ts

示例8: manageConsecutivePeriodBuffers

  /**
   * Create lazily consecutive PeriodBuffers:
   *
   * It first creates the PeriodBuffer for `basePeriod` and - once it becomes
   * full - automatically creates the next chronological one.
   * This process repeats until the PeriodBuffer linked to the last Period is
   * full.
   *
   * If an "old" PeriodBuffer becomes active again, it destroys all PeriodBuffer
   * coming after it (from the last chronological one to the first).
   *
   * To clean-up PeriodBuffers, each one of them are also automatically
   * destroyed once the clock anounce a time superior or equal to the end of
   * the concerned Period.
   *
   * A "periodBufferReady" event is sent each times a new PeriodBuffer is
   * created. The first one (for `basePeriod`) should be sent synchronously on
   * subscription.
   *
   * A "periodBufferCleared" event is sent each times a PeriodBuffer is
   * destroyed.
   * @param {string} bufferType - e.g. "audio" or "video"
   * @param {Period} basePeriod - Initial Period downloaded.
   * @param {Observable} destroy$ - Emit when/if all created Buffers from this
   * point should be destroyed.
   * @returns {Observable}
   */
  function manageConsecutivePeriodBuffers(
    bufferType : IBufferType,
    basePeriod : Period,
    destroy$ : Observable<void>
  ) : Observable<IMultiplePeriodBuffersEvent> {
    log.info("Buffer: Creating new Buffer for", bufferType, basePeriod);

    // Emits the Period of the next Period Buffer when it can be created.
    const createNextPeriodBuffer$ = new Subject<Period>();

    // Emits when the Buffers for the next Periods should be destroyed, if
    // created.
    const destroyNextBuffers$ = new Subject<void>();

    // Emits when the current position goes over the end of the current buffer.
    const endOfCurrentBuffer$ = clock$
      .pipe(filter(({ currentTime, wantedTimeOffset }) =>
        !!basePeriod.end && (currentTime + wantedTimeOffset) >= basePeriod.end
      ));

    // Create Period Buffer for the next Period.
    const nextPeriodBuffer$ = createNextPeriodBuffer$
      .pipe(exhaustMap((nextPeriod) =>
        manageConsecutivePeriodBuffers(bufferType, nextPeriod, destroyNextBuffers$)
      ));

    // Allows to destroy each created Buffer, from the newest to the oldest,
    // once destroy$ emits.
    const destroyAll$ = destroy$.pipe(
      take(1),
      tap(() => {
        // first complete createNextBuffer$ to allow completion of the
        // nextPeriodBuffer$ observable once every further Buffers have been
        // cleared.
        createNextPeriodBuffer$.complete();

        // emit destruction signal to the next Buffer first
        destroyNextBuffers$.next();
        destroyNextBuffers$.complete(); // we do not need it anymore
      }),
      share() // share side-effects
    );

    // Will emit when the current buffer should be destroyed.
    const killCurrentBuffer$ = observableMerge(endOfCurrentBuffer$, destroyAll$);

    const periodBuffer$ = PeriodBuffer({
      abrManager,
      bufferType,
      clock$,
      content: { manifest, period: basePeriod },
      garbageCollectors,
      segmentBookkeepers,
      segmentPipelinesManager,
      sourceBuffersManager,
      options,
      wantedBufferAhead$,
    }).pipe(
      mergeMap((
        evt : IPeriodBufferEvent
      ) : Observable<IMultiplePeriodBuffersEvent> => {
        const { type } = evt;
        if (type === "full-buffer") {
          const nextPeriod = manifest.getPeriodAfter(basePeriod);
          if (nextPeriod == null) {
            return observableOf(EVENTS.bufferComplete(bufferType));
          } else {
            // current buffer is full, create the next one if not
            createNextPeriodBuffer$.next(nextPeriod);
          }
        } else if (type === "active-buffer") {
          // current buffer is active, destroy next buffer if created
          destroyNextBuffers$.next();
//.........這裏部分代碼省略.........
開發者ID:canalplus,項目名稱:rx-player,代碼行數:101,代碼來源:buffer_orchestrator.ts

示例9: createExecuteCellStream

export function createExecuteCellStream(
  action$: ActionsObservable<
    | ExecuteCanceled
    | DeleteCell
    | LaunchKernelAction
    | LaunchKernelByNameAction
    | KillKernelAction
    | ExecuteCell
    | ExecuteFocusedCell
  >,
  state: any,
  message: ExecuteRequest,
  id: string,
  contentRef: ContentRef
): Observable<any> {
  const kernel = selectors.currentKernel(state);

  const channels = kernel ? kernel.channels : null;

  const kernelConnected =
    kernel &&
    channels &&
    !(kernel.status === "starting" || kernel.status === "not connected");

  if (!kernelConnected || !channels) {
    return of(
      actions.executeFailed({
        error: new Error("Kernel not connected!"),
        contentRef
      })
    );
  }

  const cellStream = executeCellStream(channels, id, message, contentRef).pipe(
    takeUntil(
      merge(
        action$.pipe(
          ofType(actions.EXECUTE_CANCELED, actions.DELETE_CELL),
          filter(
            (
              action:
                | actions.ExecuteCanceled
                | actions.DeleteCell
                | actions.LaunchKernelAction
                | actions.LaunchKernelByNameAction
                | actions.KillKernelAction
                | actions.ExecuteCell
                | actions.ExecuteFocusedCell
            ) => (action as actions.ExecuteCanceled).payload.id === id
          )
        ),
        action$.pipe(
          ofType(
            actions.LAUNCH_KERNEL,
            actions.LAUNCH_KERNEL_BY_NAME,
            actions.KILL_KERNEL
          )
        )
      )
    )
  );

  return merge(
    // We make sure to propagate back to "ourselves" the actual message
    // that we sent to the kernel with the sendExecuteRequest action
    of(actions.sendExecuteRequest({ id, message, contentRef })),
    // Merging it in with the actual stream
    cellStream
  );
}
開發者ID:kelleyblackmore,項目名稱:nteract,代碼行數:70,代碼來源:execute.ts

示例10: objectAssign

/**
 * Create clock Observable for the Buffers part of the code.
 * @param {Object} manifest
 * @param {Observable} initClock$
 * @param {Observable} initialSeek$
 * @param {Number} startTime
 * @returns {Observable}
 */
export default function createBufferClock(
  manifest : Manifest,
  initClock$ : Observable<IInitClockTick>,
  initialSeek$ : Observable<unknown>,
  speed$ : Observable<number>,
  startTime : number
) : Observable<IBufferOrchestratorClockTick> {
  let initialSeekPerformed = false;
  const updateTimeOffset$ = initialSeek$.pipe(
    tap(() => {
      initialSeekPerformed = true;
    }),
    ignoreElements()
  );

  const clock$ : Observable<IBufferOrchestratorClockTick> =
    observableCombineLatest(initClock$, speed$)
      .pipe(map(([tick, speed]) => {
        return objectAssign({
          isLive: manifest.isLive,
          liveGap: manifest.isLive ?
            manifest.getMaximumPosition() - tick.currentTime :
            Infinity,

          // wantedTimeOffset is an offset to add to the timing's current time to have
          // the "real" wanted position.
          // For now, this is seen when the media element has not yet seeked to its
          // initial position, the currentTime will most probably be 0 where the
          // effective starting position will be _startTime_.
          // Thus we initially set a wantedTimeOffset equal to startTime.
          wantedTimeOffset: initialSeekPerformed ? 0 : startTime - tick.currentTime,
          speed,
        }, tick);
      }));

  return observableMerge(clock$, updateTimeOffset$);
}
開發者ID:canalplus,項目名稱:rx-player,代碼行數:45,代碼來源:create_buffer_clock.ts


注:本文中的rxjs.merge函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。