当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript Observable.pipe方法代码示例

本文整理汇总了TypeScript中rxjs.Observable.pipe方法的典型用法代码示例。如果您正苦于以下问题:TypeScript Observable.pipe方法的具体用法?TypeScript Observable.pipe怎么用?TypeScript Observable.pipe使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在rxjs.Observable的用法示例。


在下文中一共展示了Observable.pipe方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: ngOnInit

 ngOnInit() {
   this.developerAccount$ = this.store.pipe(select(getDeveloperAccount), filterNull());
   this.status$ = this.store.pipe(select(getUpdateDeveloperAccountStatus));
   this.sub = this.status$.pipe(filter(s => s.success))
     .subscribe(ignored => this.router.navigate([ '../../' ], { relativeTo: this.route }));
 }
开发者ID:our-city-app,项目名称:plugin-mobicage-control-center,代码行数:6,代码来源:edit-developer-account.component.ts

示例2: handleSessionEvents

/**
 * listen to "message" events from session containing a challenge
 * blob and map them to licenses using the getLicense method from
 * selected keySystem.
 * @param {MediaKeySession} session
 * @param {Object} keySystem
 * @returns {Observable}
 */
export default function handleSessionEvents(
  session: MediaKeySession|ICustomMediaKeySession,
  keySystem: IKeySystemOption
) : Observable<IMediaKeySessionHandledEvents|IEMEWarningEvent> {
  log.debug("EME: Handle message events", session);

  const sessionWarningSubject$ = new Subject<IEMEWarningEvent>();
  const getLicenseRetryOptions = {
    totalRetry: 2,
    retryDelay: 200,
    errorSelector: (error: ICustomError|Error) => licenseErrorSelector(error, true),
    onRetry: (error: ICustomError|Error) =>
      sessionWarningSubject$.next({
      type: "warning",
      value: licenseErrorSelector(error, false),
    }),
  };

  const keyErrors: Observable<never> = onKeyError$(session)
    .pipe(map((error) => {
      throw new EncryptedMediaError("KEY_ERROR", error.type, true);
    }));

  const keyStatusesChanges : Observable<IMediaKeySessionEvents|IEMEWarningEvent> =
    onKeyStatusesChange$(session)
      .pipe(mergeMap((keyStatusesEvent: Event) => {
        log.debug("EME: keystatuseschange event", session, keyStatusesEvent);

        // find out possible errors associated with this event
        const warnings : IEMEWarningEvent[] = [];
        (session.keyStatuses as any).forEach((keyStatus : string, keyId : string) => {
          // Hack present because the order of the arguments has changed in spec
          // and is not the same between some versions of Edge and Chrome.
          if (keyStatus === KEY_STATUS_EXPIRED || keyId === KEY_STATUS_EXPIRED) {
            const { throwOnLicenseExpiration } = keySystem;
            const error = new EncryptedMediaError("KEY_STATUS_CHANGE_ERROR",
              "A decryption key expired", false);

            if (throwOnLicenseExpiration !== false) {
              throw error;
            }
            warnings.push({ type: "warning", value: error });
          }

          if (KEY_STATUS_ERRORS[keyId]) {
            throw new EncryptedMediaError("KEY_STATUS_CHANGE_ERROR",
              "An invalid key status has been encountered: " + keyId, true);
          } else if (KEY_STATUS_ERRORS[keyStatus]) {
            throw new EncryptedMediaError("KEY_STATUS_CHANGE_ERROR",
              "An invalid key status has been encountered: " + keyStatus, true);
          }
        });

        const warnings$ = warnings.length ? observableOf(...warnings) : EMPTY;
        const handledKeyStatusesChange$ = tryCatch(() => {
          return keySystem && keySystem.onKeyStatusesChange ?
            castToObservable(
              keySystem.onKeyStatusesChange(keyStatusesEvent, session)
            ) as Observable<TypedArray|ArrayBuffer|null> : EMPTY;
        }, undefined).pipe() // TS or RxJS Bug?
          .pipe(
            catchError((error: Error) => {
              throw new EncryptedMediaError(
                "KEY_STATUS_CHANGE_ERROR", error.toString(), true);
            }),
            map((licenseObject) => ({
              type: "key-status-change" as "key-status-change",
              value : { license: licenseObject },
            }))
          );
        return observableConcat(warnings$, handledKeyStatusesChange$);
      }));

  const keyMessages$ : Observable<IMediaKeySessionEvents> =
    onKeyMessage$(session).pipe(mergeMap((messageEvent: MediaKeyMessageEvent) => {
      const message = new Uint8Array(messageEvent.message);
      const messageType = messageEvent.messageType || "license-request";

      log.debug(`EME: Event message type ${messageType}`, session, messageEvent);

      const getLicense$ = observableDefer(() => {
        const getLicense = keySystem.getLicense(message, messageType);
        return (castToObservable(getLicense) as Observable<TypedArray|ArrayBuffer|null>)
          .pipe(
            timeout(10 * 1000),
            catchError((error : unknown) : never => {
              if (error instanceof TimeoutError) {
                throw new EncryptedMediaError("KEY_LOAD_TIMEOUT",
                  "The license server took more than 10 seconds to respond.", false);
              }
              if (error instanceof Error) {
                throw error;
//.........这里部分代码省略.........
开发者ID:canalplus,项目名称:rx-player,代码行数:101,代码来源:handle_session_events.ts

示例3: return

 return (source: Observable<T>) =>
   environment.production ? source : source.pipe(tap( // don't log in production
     d => console.log(title, 'next', d),
     e => console.log(title, 'error', e),
     () => console.log(title, 'complete')
   ));
开发者ID:ianchi,项目名称:luci-ng,代码行数:6,代码来源:observable.debug.ts

示例4: startWith

export const rootProjects: Observable<Project> = initialRootProjects.pipe(switchMap((initialRootProject: Project) =>
  projectUpdates.pipe(
    scan<Project | null, Project>((previousRootProject: Project, projectUpdate: Project | null) => previousRootProject.update(projectUpdate), initialRootProject),
    startWith(initialRootProject),)))
开发者ID:amoerie,项目名称:teamcity-theatre,代码行数:4,代码来源:settings.observables.projects.ts

示例5: expect

 observable1 = takeZone1.run(() => {
   return observable1.pipe(takeWhile((val: any) => {
     expect(Zone.current.name).toEqual(takeZone1.name);
     return val < 2;
   }));
 });
开发者ID:angular,项目名称:zone.js,代码行数:6,代码来源:rxjs.Observable.take.spec.ts

示例6: Error

  /**
   * @param {Observable} clock$
   * @param {Array.<Object>} representations
   * @returns {Observable}
   */
  public get$(
    clock$ : Observable<IRepresentationChooserClockTick>,
    representations : Representation[]
  ) : Observable<IABREstimation> {
    if (!representations.length) {
      throw new Error("ABRManager: no representation choice given");
    }
    if (representations.length === 1) {
      return observableOf({
        bitrate: undefined, // Bitrate estimation is deactivated here
        representation: representations[0],
        manual: false,
        urgent: true,
      });
    }

    const { manualBitrate$, maxAutoBitrate$, _initialBitrate }  = this;
    const _deviceEventsArray : Array<Observable<IFilters>> = [];

    if (this._limitWidth$) {
      _deviceEventsArray.push(
        this._limitWidth$
          .pipe(map(width => ({ width })))
      );
    }
    if (this._throttle$) {
      _deviceEventsArray.push(
        this._throttle$
          .pipe(map(bitrate => ({ bitrate })))
      );
    }

    // Emit restrictions on the pools of available Representations to choose
    // from.
    const deviceEvents$ : Observable<IFilters> = _deviceEventsArray.length ?
      observableCombineLatest(..._deviceEventsArray)
        .pipe(map((args : IFilters[]) => objectAssign({}, ...args))) :
      observableOf({});

    // Store the last client's bitrate generated by our estimation algorithms.
    let lastEstimatedBitrate : number|undefined;

    return manualBitrate$.pipe(switchMap(manualBitrate => {
      if (manualBitrate >= 0) {
        // -- MANUAL mode --
        return observableOf({
          bitrate: undefined, // Bitrate estimation is deactivated here
          representation: fromBitrateCeil(representations, manualBitrate) ||
            representations[0],
          manual: true,
          urgent: true, // a manual bitrate switch should happen immediately
        });
      }

      // -- AUTO mode --
      let inStarvationMode = false; // == buffer gap too low == panic mode
      return observableCombineLatest(
        clock$,
        maxAutoBitrate$,
        deviceEvents$,
        this._reEstimate$.pipe(startWith(null))
      ).pipe(
        map(([ clock, maxAutoBitrate, deviceEvents ]) => {
          let newBitrateCeil; // bitrate ceil for the chosen Representation
          let bandwidthEstimate;
          const { bufferGap, currentTime, duration } = clock;

          // check if should get in/out of starvation mode
          if (bufferGap + currentTime < duration - ABR_STARVATION_DURATION_DELTA) {
            if (!inStarvationMode && bufferGap <= ABR_STARVATION_GAP) {
              log.info("ABR: enter starvation mode.");
              inStarvationMode = true;
            } else if (inStarvationMode && bufferGap >= OUT_OF_STARVATION_GAP) {
              log.info("ABR: exit starvation mode.");
              inStarvationMode = false;
            }
          } else if (inStarvationMode) {
            log.info("ABR: exit starvation mode.");
            inStarvationMode = false;
          }

          // If in starvation mode, check if a quick new estimate can be done
          // from the last requests.
          // If so, cancel previous estimations and replace it by the new one
          if (inStarvationMode) {
            bandwidthEstimate = estimateStarvationModeBitrate(
              this._currentRequests, clock, lastEstimatedBitrate);

            if (bandwidthEstimate != null) {
              log.info("ABR: starvation mode emergency estimate:", bandwidthEstimate);
              this.estimator.reset();
              const currentBitrate = clock.downloadBitrate;
              newBitrateCeil = currentBitrate == null ?
                Math.min(bandwidthEstimate, maxAutoBitrate) :
                Math.min(bandwidthEstimate, maxAutoBitrate, currentBitrate);
//.........这里部分代码省略.........
开发者ID:canalplus,项目名称:rx-player,代码行数:101,代码来源:representation_chooser.ts

示例7: objectAssign

/**
 * Create new Buffer Observable linked to the given Adaptation.
 *
 * It will rely on the ABRManager to choose at any time the best Representation
 * for this Adaptation and then run the logic to download and push the
 * corresponding segments in the SourceBuffer.
 *
 * It will emit various events to report its status to the caller.
 *
 * @param {Observable} clock$ - Clock at which the Buffer will check for
 * segments download
 * @param {QueuedSourceBuffer} queuedSourceBuffer - QueuedSourceBuffer used
 * to push segments and know about the current real buffer's health.
 * @param {SegmentBookkeeper} segmentBookkeeper - Used to synchronize and
 * retrieve the Segments currently present in the QueuedSourceBuffer
 * @param {Function} segmentFetcher - Function used to download segments
 * @param {Observable} wantedBufferAhead$ - Emits the buffer goal
 * @param {Object} content - Content to download
 * @param {Object} abrManager
 * @returns {Observable}
 */
export default function AdaptationBuffer<T>(
  clock$ : Observable<IAdaptationBufferClockTick>,
  queuedSourceBuffer : QueuedSourceBuffer<T>,
  segmentBookkeeper : SegmentBookkeeper,
  segmentFetcher : IPrioritizedSegmentFetcher<T>,
  wantedBufferAhead$ : Observable<number>,
  content : {
    manifest : Manifest;
    period : Period; adaptation : Adaptation;
  },
  abrManager : ABRManager,
  options : { manualBitrateSwitchingMode : "seamless"|"direct" }
) : Observable<IAdaptationBufferEvent<T>> {
  const directManualBitrateSwitching = options.manualBitrateSwitchingMode === "direct";
  const { manifest, period, adaptation } = content;

  // Keep track of the currently considered representation to add informations
  // to the ABR clock.
  let currentRepresentation : Representation|null = null;

  const abrClock$ = clock$.pipe(map((tick) => {
    const downloadBitrate = currentRepresentation ?
      currentRepresentation.bitrate : undefined;
    return objectAssign({ downloadBitrate }, tick);
  }));

  const abr$ : Observable<IABREstimation> =
    abrManager.get$(adaptation.type, abrClock$, adaptation.representations)
      .pipe(observeOn(asapScheduler), share());

  // emit when the current RepresentationBuffer should be stopped right now
  const killCurrentBuffer$ = new Subject<void>();

  // emit when the current RepresentationBuffer should stop making new downloads
  const terminateCurrentBuffer$ = new Subject<void>();

  // Emit at each bitrate estimate done by the ABRManager
  const bitrateEstimate$ = abr$.pipe(
    filter(({ bitrate }) => bitrate != null),
    distinctUntilChanged((old, current) => old.bitrate === current.bitrate),
    map(({ bitrate }) => {
      log.debug(`Buffer: new ${adaptation.type} bitrate estimation`, bitrate);
      return EVENTS.bitrateEstimationChange(adaptation.type, bitrate);
    })
  );

  const newRepresentation$ = abr$
    .pipe(distinctUntilChanged((a, b) =>
      a.manual === b.manual && a.representation.id === b.representation.id
    ));

  const adaptationBuffer$ = observableMerge(
    newRepresentation$
      .pipe(concatMapLatest((estimate, i) : Observable<IAdaptationBufferEvent<T>> => {
        const { representation } = estimate;
        currentRepresentation = representation;

        // Manual switch needs an immediate feedback.
        // To do that properly, we need to reload the MediaSource
        if (directManualBitrateSwitching && estimate.manual && i !== 0) {
          return observableOf(EVENTS.needsMediaSourceReload());
        }
        const representationChange$ = observableOf(
          EVENTS.representationChange(adaptation.type, period, representation));
        const representationBuffer$ = createRepresentationBuffer(representation)
          .pipe(takeUntil(killCurrentBuffer$));
        return observableConcat(representationChange$, representationBuffer$);
      })),
    newRepresentation$.pipe(map((estimation, i) => {
      if (i === 0) { // no buffer pending
        return;
      }
      if (estimation.urgent) {
        log.info("Buffer: urgent Representation switch", adaptation.type);

        // kill current buffer after concatMapLatest has been called
        killCurrentBuffer$.next();
      } else {
        log.info("Buffer: slow Representation switch", adaptation.type);
//.........这里部分代码省略.........
开发者ID:canalplus,项目名称:rx-player,代码行数:101,代码来源:adaptation_buffer.ts

示例8: expect

 observable1 = everyZone1.run(() => {
   return observable1.pipe(every((v: any) => {
     expect(Zone.current.name).toEqual(everyZone1.name);
     return v % 2 === 0;
   }));
 });
开发者ID:angular,项目名称:zone.js,代码行数:6,代码来源:rxjs.Observable.collection.spec.ts


注:本文中的rxjs.Observable.pipe方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。