takeWhile

signature: takeWhile(predicate: function(value, index): boolean): Observable

Emit values until provided expression is false.

takeWhile - 图1

Examples

Example 1: Take values under limit

( jsBin |
jsFiddle )

  1. import { of } from 'rxjs/observable/of';
  2. import { takeWhile } 'rxjs/operators';
  3. //emit 1,2,3,4,5
  4. const source = of(1, 2, 3, 4, 5);
  5. //allow values until value from source is greater than 4, then complete
  6. const example = source.pipe(takeWhile(val => val <= 4));
  7. //output: 1,2,3,4
  8. const subscribe = example.subscribe(val => console.log(val));
Example 2: Difference between takeWhile() and filter()

( jsBin |
jsFiddle )

  1. import { of } from 'rxjs/observable/of';
  2. import { takeWhile, filter } 'rxjs/operators';
  3. // emit 3, 3, 3, 9, 1, 4, 5, 8, 96, 3, 66, 3, 3, 3
  4. const source = of(3, 3, 3, 9, 1, 4, 5, 8, 96, 3, 66, 3, 3, 3);
  5. // allow values until value from source equals 3, then complete
  6. // output: [3, 3, 3]
  7. source
  8. .pipe(takeWhile(it => it === 3))
  9. .subscribe(val => console.log('takeWhile', val))
  10. // output: [3, 3, 3, 3, 3, 3, 3]
  11. source
  12. .pipe(filter(it => it === 3))
  13. .subscribe(val => console.log('filter', val));

Additional Resources


:file_folder: Source Code:
https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/takeWhile.ts