takeUntil

签名: takeUntil(notifier: Observable): Observable

发出值,直到提供的 observable 发出值,它便完成。


:bulb: 如果你只需要指定数量的值,试试 take


takeUntil - 图2

示例

示例 1: 取值直到 timer 发出

( jsBin |
jsFiddle )

  1. import { interval } from 'rxjs/observable/interval';
  2. import { timer } from 'rxjs/observable/timer';
  3. import { takeUntil } 'rxjs/operators';
  4. // 每1秒发出值
  5. const source = interval(1000);
  6. // 5秒后发出值
  7. const timer = timer(5000);
  8. // 当5秒后 timer 发出值时, source 则完成
  9. const example = source.pipe(takeUntil(timer));
  10. // 输出: 0,1,2,3
  11. const subscribe = example.subscribe(val => console.log(val));
示例 2: 取前5个偶数

( jsBin |
jsFiddle )

  1. import { interval } from 'rxjs/observable/interval';
  2. import { takeUntil, filter, scan, map, withLatestFrom } 'rxjs/operators';
  3. // 每1秒发出值
  4. const source = interval(1000);
  5. // 是偶数吗?
  6. const isEven = val => val % 2 === 0;
  7. // 只允许是偶数的值
  8. const evenSource = source.pipe(filter(isEven));
  9. // 保存运行中的偶数数量
  10. const evenNumberCount = evenSource.pipe(scan((acc, _) => acc + 1, 0));
  11. // 不发出直到发出过5个偶数
  12. const fiveEvenNumbers = evenNumberCount.pipe(filter(val => val > 5));
  13. const example = evenSource.pipe(
  14. // 还给出当前偶数的数量以用于显示
  15. withLatestFrom(evenNumberCount),
  16. map(([val, count]) => `Even number (${count}) : ${val}`),
  17. // 当发出了5个偶数时,source 则完成
  18. takeUntil(fiveEvenNumbers)
  19. )
  20. /*
  21. Even number (1) : 0,
  22. Even number (2) : 2
  23. Even number (3) : 4
  24. Even number (4) : 6
  25. Even number (5) : 8
  26. */
  27. const subscribe = example.subscribe(val => console.log(val));

其他资源


:file_folder: 源码: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/takeUntil.ts