takeUntil

signature: takeUntil(notifier: Observable): Observable

Emit values until provided observable emits.


:bulb: If you only need a specific number of values, try take!


takeUntil - 图2

Examples

Example 1: Take values until timer emits

( jsBin |
jsFiddle )

  1. import { interval } from 'rxjs/observable/interval';
  2. import { timer } from 'rxjs/observable/timer';
  3. import { takeUntil } 'rxjs/operators';
  4. //emit value every 1s
  5. const source = interval(1000);
  6. //after 5 seconds, emit value
  7. const timer = timer(5000);
  8. //when timer emits after 5s, complete source
  9. const example = source.pipe(takeUntil(timer));
  10. //output: 0,1,2,3
  11. const subscribe = example.subscribe(val => console.log(val));
Example 2: Take the first 5 even numbers

( jsBin |
jsFiddle )

  1. import { interval } from 'rxjs/observable/interval';
  2. import { takeUntil, filter, scan, map, withLatestFrom } 'rxjs/operators';
  3. //emit value every 1s
  4. const source = interval(1000);
  5. //is number even?
  6. const isEven = val => val % 2 === 0;
  7. //only allow values that are even
  8. const evenSource = source.pipe(filter(isEven));
  9. //keep a running total of the number of even numbers out
  10. const evenNumberCount = evenSource.pipe(scan((acc, _) => acc + 1, 0));
  11. //do not emit until 5 even numbers have been emitted
  12. const fiveEvenNumbers = evenNumberCount.pipe(filter(val => val > 5));
  13. const example = evenSource.pipe(
  14. //also give me the current even number count for display
  15. withLatestFrom(evenNumberCount),
  16. map(([val, count]) => `Even number (${count}) : ${val}`),
  17. //when five even numbers have been emitted, complete source observable
  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));

Additional Resources


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