Learn RxJS
Search…
takeUntil

signature: takeUntil(notifier: Observable): Observable

Emit values until provided observable emits.

πŸ’‘ If you only need a specific number of values, try take!
​​
​
​

Examples

Example 1: Take values until timer emits
1
// RxJS v6+
2
import { interval, timer } from 'rxjs';
3
import { takeUntil } from 'rxjs/operators';
4
​
5
//emit value every 1s
6
const source = interval(1000);
7
//after 5 seconds, emit value
8
const timer$ = timer(5000);
9
//when timer emits after 5s, complete source
10
const example = source.pipe(takeUntil(timer$));
11
//output: 0,1,2,3
12
const subscribe = example.subscribe(val => console.log(val));
Copied!
Example 2: Take the first 5 even numbers
1
// RxJS v6+
2
import { interval } from 'rxjs/observable/interval';
3
import { takeUntil, filter, scan, map, withLatestFrom } from 'rxjs/operators';
4
​
5
//emit value every 1s
6
const source = interval(1000);
7
//is number even?
8
const isEven = val => val % 2 === 0;
9
//only allow values that are even
10
const evenSource = source.pipe(filter(isEven));
11
//keep a running total of the number of even numbers out
12
const evenNumberCount = evenSource.pipe(scan((acc, _) => acc + 1, 0));
13
//do not emit until 5 even numbers have been emitted
14
const fiveEvenNumbers = evenNumberCount.pipe(filter(val => val > 5));
15
​
16
const example = evenSource.pipe(
17
//also give me the current even number count for display
18
withLatestFrom(evenNumberCount),
19
map(([val, count]) => `Even number (${count}) : ${val}`),
20
//when five even numbers have been emitted, complete source observable
21
takeUntil(fiveEvenNumbers)
22
);
23
/*
24
Even number (1) : 0,
25
Even number (2) : 2
26
Even number (3) : 4
27
Even number (4) : 6
28
Even number (5) : 8
29
*/
30
const subscribe = example.subscribe(val => console.log(val));
Copied!
Example 3: Take mouse events on mouse down until mouse up
1
// RxJS v6+
2
import { fromEvent } from 'rxjs';
3
import { takeUntil, mergeMap, map } from 'rxjs/operators';
4
​
5
const mousedown$ = fromEvent(document, 'mousedown');
6
const mouseup$ = fromEvent(document, 'mouseup');
7
const mousemove$ = fromEvent(document, 'mousemove');
8
​
9
// after mousedown, take position until mouse up
10
mousedown$
11
.pipe(
12
mergeMap(_ => {
13
return mousemove$.pipe(
14
map((e: any) => ({
15
x: e.clientX,
16
y: e.clientY
17
})),
18
// complete inner observable on mouseup event
19
takeUntil(mouseup$)
20
);
21
})
22
)
23
.subscribe(console.log);
Copied!

Additional Resources

Last modified 6mo ago