• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript operators.takeWhile函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中rxjs/operators.takeWhile函数的典型用法代码示例。如果您正苦于以下问题:TypeScript takeWhile函数的具体用法?TypeScript takeWhile怎么用?TypeScript takeWhile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: pollForChanges

  pollForChanges(seriesImport: SeriesImportModel): Observable<SeriesImportModel> {

    let lastReceived = null;

    let seriesImportPoller = interval(1000)
      .pipe(
        flatMap(() => {
          return seriesImport.doc.reload();
        }),
        map(doc => {
          let parentAccountDoc = seriesImport.parent;
          seriesImport.init(parentAccountDoc, doc, false);
          return new SeriesImportModel(parentAccountDoc, doc);
        }),
        takeWhile((si) => {
          // HACK
          // https://github.com/ReactiveX/rxjs/issues/2420
          // TODO fixed in rxjs 6
          if (lastReceived !== null) {
            return false;
          }
          if (si.isFinished()) {
            lastReceived = si;
          }
          return true;
        })
      );

    return concat(
      observableOf(seriesImport),
      seriesImportPoller
    );
  }
开发者ID:PRX,项目名称:publish.prx.org,代码行数:33,代码来源:series-import.service.ts


示例2: takeWhile1

 takeWhile1() {
   // emit 1,2,3,4,5
   const source = of(1, 2, 3, 4, 5);
   // allow values until value from source is greater than 4, then complete
   const example = source.pipe(takeWhile(val => val <= 4));
   // output: 1,2,3,4
   const subscribe = example.subscribe(val => console.log(val));
 }
开发者ID:zwvista,项目名称:SampleMisc,代码行数:8,代码来源:conditional.service.ts


示例3: it

  it('file replacements work with watch mode', async () => {
    const overrides = {
      fileReplacements: [
        {
          replace: normalize('/src/meaning.ts'),
          with: normalize('/src/meaning-too.ts'),
        },
      ],
      watch: true,
    };

    let buildCount = 0;
    let phase = 1;

    const run = await architect.scheduleTarget(target, overrides);
    await run.output.pipe(
      timeout(30000),
      tap((result) => {
        expect(result.success).toBe(true, 'build should succeed');

        const fileName = normalize('dist/main.js');
        const content = virtualFs.fileBufferToString(host.scopedSync().read(fileName));
        const has42 = /meaning\s*=\s*42/.test(content);
        buildCount++;
        switch (phase) {
          case 1:
            const has10 = /meaning\s*=\s*10/.test(content);

            if (has42 && !has10) {
              phase = 2;
              host.writeMultipleFiles({
                'src/meaning-too.ts': 'export var meaning = 84;',
              });
            }
            break;

          case 2:
            const has84 = /meaning\s*=\s*84/.test(content);

            if (has84 && !has42) {
              phase = 3;
            } else {
              // try triggering a rebuild again
              host.writeMultipleFiles({
                'src/meaning-too.ts': 'export var meaning = 84;',
              });
            }
            break;
        }
      }),
      takeWhile(() => phase < 3),
    ).toPromise().catch(() => {
      throw new Error(`stuck at phase ${phase} [builds: ${buildCount}]`);
    });

    await run.stop();
  });
开发者ID:angular,项目名称:angular-cli,代码行数:57,代码来源:replacements_spec_large.ts


示例4: switchMap

 switchMap(() => merge( // then emit every 500ms, and when the navigation ends or cancels or errors. This delay must
                        // match the transition duration in the .scss file
   timer(0, 500).pipe(
     map(i => 100 - (100 / Math.pow(2, i))), // emit 0 then 50, 75, 87.5, etc.
     takeWhile(i => i < 99.95), // stop because that just triggers change detection with no visual change anymore
     takeUntil(end$), // but stop emitting every 500ms when the navigation ends or cancels or errors
     map(i => ({ value: i }))
   ),
   end$.pipe(first(), map(() => null)) // set back to null when the navigation ends or cancels or errors to hide
                                       // the progress bar
 ))
开发者ID:Ninja-Squad,项目名称:globe42,代码行数:11,代码来源:navigation-progress.component.ts


示例5: it

  it('file replacements work with watch mode', (done) => {
    const overrides = {
      fileReplacements: [
        {
          replace: normalize('/src/meaning.ts'),
          with: normalize('/src/meaning-too.ts'),
        },
      ],
      watch: true,
    };

    let buildCount = 0;
    let phase = 1;
    runTargetSpec(host, browserTargetSpec, overrides, 30000).pipe(
      tap((buildEvent) => expect(buildEvent.success).toBe(true, 'build should succeed')),
      tap(() => {
        const fileName = join(outputPath, 'main.js');
        const content = virtualFs.fileBufferToString(host.scopedSync().read(fileName));
        const has42 = /meaning\s*=\s*42/.test(content);
        buildCount++;
        switch (phase) {
          case 1:
            const has10 = /meaning\s*=\s*10/.test(content);

            if (has42 && !has10) {
              phase = 2;
              host.writeMultipleFiles({
                'src/meaning-too.ts': 'export var meaning = 84;',
              });
            }
            break;

          case 2:
            const has84 = /meaning\s*=\s*84/.test(content);

            if (has84 && !has42) {
              phase = 3;
            } else {
              // try triggering a rebuild again
              host.writeMultipleFiles({
                'src/meaning-too.ts': 'export var meaning = 84;',
              });
            }
            break;
        }
      }),
      takeWhile(() => phase < 3),
    ).toPromise().then(
      () => done(),
      () => done.fail(`stuck at phase ${phase} [builds: ${buildCount}]`),
    );
  });
开发者ID:DevIntent,项目名称:angular-cli,代码行数:52,代码来源:replacements_spec_large.ts


示例6: it

  it('rebuilds TS worker', async () => {
    host.writeMultipleFiles(workerFiles);
    const overrides = {
      webWorkerTsConfig: 'src/tsconfig.worker.json',
      watch: true,
    };

    let buildCount = 0;
    let phase = 1;
    const workerPath = join(outputPath, '0.worker.js');
    let workerContent = '';

    const run = await architect.scheduleTarget(target, overrides);
    await run.output.pipe(
      // Wait for files to be written to disk.
      debounceTime(1000),
      tap((buildEvent) => expect(buildEvent.success).toBe(true, 'build should succeed')),
      tap(() => {
        buildCount++;
        switch (phase) {
          case 1:
            // Original worker content should be there.
            workerContent = virtualFs.fileBufferToString(host.scopedSync().read(workerPath));
            expect(workerContent).toContain('bar');
            // Change content of worker dependency.
            host.writeMultipleFiles({ 'src/app/dep.ts': `export const foo = 'baz';` });
            phase = 2;
            break;

          case 2:
            workerContent = virtualFs.fileBufferToString(host.scopedSync().read(workerPath));
            // TODO(filipesilva): Should this change? Check with Jason Miller.
            // The worker changes name with each rebuild. But sometimes it also changes from 0 to
            // 1 and then back to 0. It's hard to know where the updated content is, but it should
            // be in one of these two.
            const anotherWorkerPath = join(outputPath, '1.worker.js');
            const anotherWorkerContent = virtualFs.fileBufferToString(
              host.scopedSync().read(anotherWorkerPath));
            // Worker content should have changed.
            expect(
              workerContent.includes('baz') || anotherWorkerContent.includes('baz'),
            ).toBeTruthy('Worker bundle did not contain updated content.');
            phase = 3;
            break;
        }
      }),
      takeWhile(() => phase < 3),
    ).toPromise();
    await run.stop();
  });
开发者ID:angular,项目名称:angular-cli,代码行数:50,代码来源:web-worker_spec_large.ts


示例7: pollRendition

 private pollRendition(nodeId: string, encoding: string, intervalSize: number = 1000, retries: number = 5) {
     let attempts = 0;
     return interval(intervalSize)
         .pipe(
             switchMap(() => this.getRendition(nodeId, encoding)),
             takeWhile((renditionEntry: RenditionEntry) => {
                 attempts += 1;
                 if (attempts > retries) {
                     return false;
                 }
                 return (renditionEntry.entry.status.toString() !== 'CREATED');
             })
         );
 }
开发者ID:Alfresco,项目名称:alfresco-ng2-components,代码行数:14,代码来源:renditions.service.ts


示例8: takeWhile2

  takeWhile2() {
    //  emit 3, 3, 3, 9, 1, 4, 5, 8, 96, 3, 66, 3, 3, 3
    const source = of(3, 3, 3, 9, 1, 4, 5, 8, 96, 3, 66, 3, 3, 3);

    //  allow values until value from source equals 3, then complete
    //  output: [3, 3, 3]
    source
      .pipe(takeWhile(it => it === 3))
      .subscribe(val => console.log('takeWhile', val));

    //  output: [3, 3, 3, 3, 3, 3, 3]
    source
      .pipe(filter(it => it === 3))
      .subscribe(val => console.log('filter', val));
  }
开发者ID:zwvista,项目名称:SampleMisc,代码行数:15,代码来源:conditional.service.ts


示例9: function

 return function (errors: Observable<any>): Observable<any> { //該函數主要功能就是要每隔[delayT]秒試一次,不超[attempts]次
   return errors.pipe(
     scan((acc, value) => {
       console.log(acc, value);
       acc += 1;
       if (acc < attempts) {
         return acc;
       } else {
         throw new Error(''+value);
       }
     }, 0),
     takeWhile((acc => acc < attempts)),
     delay(delayT)
   );
 };
开发者ID:Ed-Lee,项目名称:PS-RxJS,代码行数:15,代码来源:data.service.ts


示例10: it

  it('recovers from compilation failures in watch mode', async () => {
    let buildCount = 0;
    let phase = 1;

    // The current linux-based CI environments may not fully settled in regards to filesystem
    // changes from previous tests which reuse the same directory and fileset.
    // The initial delay helps mitigate false positive rebuild triggers in such scenarios.
    const { run } = await timer(1000).pipe(
      switchMap(() => architect.scheduleTarget(karmaTargetSpec, { watch: true })),
      switchMap(run => run.output.pipe(map(output => ({ run, output })))),
      debounceTime(500),
      tap(({ output }) => {
        buildCount += 1;
        switch (phase) {
          case 1:
            // Karma run should succeed.
            // Add a compilation error.
            expect(output.success).toBe(true);
            // Add an syntax error to a non-main file.
            host.appendToFile('src/app/app.component.spec.ts', `]]]`);
            phase = 2;
            break;

          case 2:
            // Karma run should fail due to compilation error. Fix it.
            expect(output.success).toBe(false);
            host.replaceInFile('src/app/app.component.spec.ts', `]]]`, '');
            phase = 3;
            break;

          case 3:
            // Karma run should succeed again.
            expect(output.success).toBe(true);
            phase = 4;
            break;
        }
      }),
      takeWhile(() => phase < 4),
      catchError((_, caught) => {
        fail(`stuck at phase ${phase} [builds: ${buildCount}]`);

        return caught;
      }),
    ).toPromise();

    await run.stop();
  });
开发者ID:angular,项目名称:angular-cli,代码行数:47,代码来源:rebuilds_spec_large.ts


示例11: it

  it('should NOT handle hot inner empty', (done: MochaDone) => {
    const source = of(1, 2, 3, 4, 5, 6, 7, 8, 9);
    const closing = EMPTY;
    const TOO_MANY_INVOCATIONS = 30;

    source.pipe(
      bufferWhen(() => closing),
      takeWhile((val: any, index: number) => index < TOO_MANY_INVOCATIONS)
    ).subscribe((val: any) => {
      expect(Array.isArray(val)).to.be.true;
      expect(val.length).to.equal(0);
    }, (err: any) => {
      done(new Error('should not be called'));
    }, () => {
      done();
    });
  });
开发者ID:DallanQ,项目名称:rxjs,代码行数:17,代码来源:bufferWhen-spec.ts


示例12: switchMap4

  switchMap4() {
    const countdownSeconds = 10;
    const setHTML = id => val => (document.getElementById(id).innerHTML = val);
    const pauseButton = document.getElementById('pause');
    const resumeButton = document.getElementById('resume');
    const interval$ = interval(1000).pipe(mapTo(-1));

    const pause$ = fromEvent(pauseButton, 'click').pipe(mapTo(false));
    const resume$ = fromEvent(resumeButton, 'click').pipe(mapTo(true));

    const timer$ = merge(pause$, resume$)
      .pipe(
        startWith(true),
        switchMap(val => (val ? interval$ : EMPTY)),
        scan((acc, curr) => (curr ? curr + acc : acc), countdownSeconds),
        takeWhile(v => v >= 0)
      )
      .subscribe(setHTML('remaining'));
  }
开发者ID:zwvista,项目名称:SampleMisc,代码行数:19,代码来源:transforming.service.ts


示例13: it

  it('recovers from compilation failures in watch mode', (done) => {
    const overrides = { watch: true };
    let buildCount = 0;
    let phase = 1;

    runTargetSpec(host, karmaTargetSpec, overrides, DefaultTimeout * 3).pipe(
      debounceTime(500),
      tap((buildEvent) => {
        buildCount += 1;
        switch (phase) {
          case 1:
            // Karma run should succeed.
            // Add a compilation error.
            expect(buildEvent.success).toBe(true);
            // Add an syntax error to a non-main file.
            host.appendToFile('src/app/app.component.spec.ts', `]]]`);
            phase = 2;
            break;

          case 2:
            // Karma run should fail due to compilation error. Fix it.
            expect(buildEvent.success).toBe(false);
            host.replaceInFile('src/app/app.component.spec.ts', `]]]`, '');
            phase = 3;
            break;

          case 3:
            // Karma run should succeed again.
            expect(buildEvent.success).toBe(true);
            phase = 4;
            break;
        }
      }),
      takeWhile(() => phase < 4),
    ).toPromise().then(
      () => done(),
      () => done.fail(`stuck at phase ${phase} [builds: ${buildCount}]`),
    );
  });
开发者ID:DevIntent,项目名称:angular-cli,代码行数:39,代码来源:rebuilds_spec_large.ts


示例14: it

  it('should stop listening to a synchronous observable when unsubscribed', () => {
    const sideEffects: number[] = [];
    const synchronousObservable = concat(
      defer(() => {
        sideEffects.push(1);
        return of(1);
      }),
      defer(() => {
        sideEffects.push(2);
        return of(2);
      }),
      defer(() => {
        sideEffects.push(3);
        return of(3);
      })
    );

    of(null).pipe(
      exhaustMap(() => synchronousObservable),
      takeWhile((x) => x != 2) // unsubscribe at the second side-effect
    ).subscribe(() => { /* noop */ });

    expect(sideEffects).to.deep.equal([1, 2]);
  });
开发者ID:jaychsu,项目名称:RxJS,代码行数:24,代码来源:exhaustMap-spec.ts


示例15: it

  it('should stop listening to a synchronous observable when unsubscribed', () => {
    const sideEffects: number[] = [];
    const synchronousObservable = concat(
      defer(() => {
        sideEffects.push(1);
        return of(1);
      }),
      defer(() => {
        sideEffects.push(2);
        return of(2);
      }),
      defer(() => {
        sideEffects.push(3);
        return of(3);
      })
    );

    throwError(new Error('Some error')).pipe(
      onErrorResumeNext(synchronousObservable),
      takeWhile((x) => x != 2) // unsubscribe at the second side-effect
    ).subscribe(() => { /* noop */ });

    expect(sideEffects).to.deep.equal([1, 2]);
  });
开发者ID:jaychsu,项目名称:RxJS,代码行数:24,代码来源:onErrorResumeNext-spec.ts


示例16: higherOrder

export function takeWhile<T>(this: Observable<T>, predicate: (value: T, index: number) => boolean): Observable<T> {
  return higherOrder(predicate)(this);
}
开发者ID:DallanQ,项目名称:rxjs,代码行数:3,代码来源:takeWhile.ts


示例17: it

  it('rebuilds on TS file changes', (done) => {
    const goldenValueFiles: { [path: string]: string } = {
      'src/app/app.module.ts': `
        import { BrowserModule } from '@angular/platform-browser';
        import { NgModule } from '@angular/core';

        import { AppComponent } from './app.component';

        @NgModule({
          declarations: [
            AppComponent
          ],
          imports: [
            BrowserModule
          ],
          providers: [],
          bootstrap: [AppComponent]
        })
        export class AppModule { }

        console.log('$$_E2E_GOLDEN_VALUE_1');
        export let X = '$$_E2E_GOLDEN_VALUE_2';
      `,
      'src/main.ts': `
        import { enableProdMode } from '@angular/core';
        import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

        import { AppModule } from './app/app.module';
        import { environment } from './environments/environment';

        if (environment.production) {
          enableProdMode();
        }

        platformBrowserDynamic().bootstrapModule(AppModule);

        import * as m from './app/app.module';
        console.log(m.X);
        console.log('$$_E2E_GOLDEN_VALUE_3');
      `,
    };

    const overrides = { watch: true };

    let buildCount = 0;
    let phase = 1;
    runTargetSpec(host, browserTargetSpec, overrides, DefaultTimeout * 3).pipe(
      tap((buildEvent) => expect(buildEvent.success).toBe(true, 'build should succeed')),
      tap(() => {
        buildCount++;
        const hasLazyChunk = host.scopedSync().exists(join(outputPath, 'lazy-lazy-module.js'));
        switch (phase) {
          case 1:
            // No lazy chunk should exist.
            if (!hasLazyChunk) {
              phase = 2;
              host.writeMultipleFiles({ ...lazyModuleFiles, ...lazyModuleImport });
            }
            break;

          case 2:
            // A lazy chunk should have been with the filename.
            if (hasLazyChunk) {
              phase = 3;
              host.writeMultipleFiles(goldenValueFiles);
            }
            break;

          case 3:
            // The golden values should be present and in the right order.
            const re = new RegExp(
              /\$\$_E2E_GOLDEN_VALUE_1(.|\n|\r)*/.source
              + /\$\$_E2E_GOLDEN_VALUE_2(.|\n|\r)*/.source
              + /\$\$_E2E_GOLDEN_VALUE_3/.source,
            );
            const fileName = './dist/main.js';
            const content = virtualFs.fileBufferToString(
              host.scopedSync().read(normalize(fileName)),
            );

            if (re.test(content)) {
              phase = 4;
            }
            break;
        }
      }),
      takeWhile(() => phase < 4),
      ).toPromise().then(
        () => done(),
        () => done.fail(`stuck at phase ${phase} [builds: ${buildCount}]`),
      );
  });
开发者ID:DevIntent,项目名称:angular-cli,代码行数:92,代码来源:rebuild_spec_large.ts


示例18: 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


示例19: it

it('should support a user-defined type guard', () => {
  const o = of('foo').pipe(takeWhile((s): s is 'foo' => true)); // $ExpectType Observable<"foo">
});
开发者ID:jaychsu,项目名称:RxJS,代码行数:3,代码来源:takeWhile-spec.ts


示例20: getBufferPaddings


//.........这里部分代码省略.........

        return observableConcat(
          observableOf(...neededActions),
          status.isFull ? observableOf(EVENTS.fullBuffer(bufferType)) : EMPTY
        );
      }

      if (!currentSegmentRequest) {
        log.debug("Buffer: start downloading queue.", bufferType);
        downloadQueue = neededSegments;
        startQueue$.next(); // restart the queue
      } else if (currentSegmentRequest.segment.id !== mostNeededSegment.segment.id) {
        log.debug("Buffer: restart download queue.", bufferType);
        downloadQueue = neededSegments;
        startQueue$.next(); // restart the queue
      } else if (currentSegmentRequest.priority !== mostNeededSegment.priority) {
        log.debug("Buffer: update request priority.", bufferType);
        const { request$ } = currentSegmentRequest;
        segmentFetcher.updatePriority(request$, mostNeededSegment.priority);
        currentSegmentRequest.priority = mostNeededSegment.priority;
      } else {
        log.debug("Buffer: update downloading queue", bufferType);

        // Update the previous queue to be all needed segments but the first one,
        // for which a request is already pending
        downloadQueue = neededSegments.slice().splice(1, neededSegments.length);
      }

      return observableConcat(
        observableOf(...neededActions),
        observableOf(EVENTS.activeBuffer(bufferType))
      );
    }),
    takeWhile((e) : e is IBufferNeededActions|IBufferStateFull|IBufferStateActive =>
      e.type !== "terminated"
    )
  );

  // Buffer Queue:
  //   - download every segments queued sequentially
  //   - append them to the SourceBuffer
  const bufferQueue$ = startQueue$.pipe(
    switchMap(() => downloadQueue.length ? loadSegmentsFromQueue() : EMPTY),
    mergeMap(appendSegment)
  );

  return observableMerge(status$, bufferQueue$).pipe(share());

  /**
   * Request every Segment in the ``downloadQueue`` on subscription.
   * Emit the data of a segment when a request succeeded.
   *
   * Important side-effects:
   *   - Mutates `currentSegmentRequest` when doing and finishing a request.
   *   - Will emit from finishedDownloadQueue$ Subject after it's done.
   * @returns {Observable}
   */
  function loadSegmentsFromQueue() : Observable<ILoadedSegmentObject<T>> {
    const requestNextSegment$ : Observable<ILoadedSegmentObject<T>> =
      observableDefer(() => {
        const currentNeededSegment = downloadQueue.shift();
        if (currentNeededSegment == null) {
          nextTick(() => { finishedDownloadQueue$.next(); });
          return EMPTY;
        }
开发者ID:canalplus,项目名称:rx-player,代码行数:66,代码来源:representation_buffer.ts



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript operators.tap函数代码示例发布时间:2022-05-25
下一篇:
TypeScript operators.takeUntil函数代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap