Learn RxJS
Search…
takeWhile

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

Emit values until provided expression is false.

πŸ’‘ When the optional inclusive parameter is set to true it will also emit the first item that didn't pass the predicate.
​​
​
​

Examples

Example 1: Take values under limit
1
// RxJS v6+
2
import { of } from 'rxjs';
3
import { takeWhile } from 'rxjs/operators';
4
​
5
//emit 1,2,3,4,5
6
const source$ = of(1, 2, 3, 4, 5);
7
​
8
//allow values until value from source is greater than 4, then complete
9
source$
10
.pipe(takeWhile(val => val <= 4))
11
// log: 1,2,3,4
12
.subscribe(val => console.log(val));
Copied!
Example 2: (v6.4+) takeWhile with inclusive flag
1
// RxJS v6.4+
2
import { of } from 'rxjs';
3
import { takeWhile, filter } from 'rxjs/operators';
4
​
5
const source$ = of(1, 2, 3, 9);
6
​
7
source$
8
// with inclusive flag, the value causing the predicate to return false will also be emitted
9
.pipe(takeWhile(val => val <= 3, true))
10
// log: 1, 2, 3, 9
11
.subscribe(console.log);
Copied!
Example 3: Difference between takeWhile and filter
1
// RxJS v6+
2
import { of } from 'rxjs';
3
import { takeWhile, filter } from 'rxjs/operators';
4
​
5
// emit 3, 3, 3, 9, 1, 4, 5, 8, 96, 3, 66, 3, 3, 3
6
const source$ = of(3, 3, 3, 9, 1, 4, 5, 8, 96, 3, 66, 3, 3, 3);
7
​
8
// allow values until value from source equals 3, then complete
9
source$
10
.pipe(takeWhile(it => it === 3))
11
// log: 3, 3, 3
12
.subscribe(val => console.log('takeWhile', val));
13
​
14
source$
15
.pipe(filter(it => it === 3))
16
// log: 3, 3, 3, 3, 3, 3, 3
17
.subscribe(val => console.log('filter', val));
Copied!

Additional Resources

Last modified 1yr ago