当前位置: 首页>>代码示例>>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;未经允许,请勿转载。