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


TypeScript operators.takeWhile函数代码示例

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


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


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