Learn RxJS
Search…
first

signature: first(predicate: function, select: function)

Emit the first value or first to pass provided expression.

πŸ’‘ The counterpart to first is last!
πŸ’‘ First will deliver an EmptyError to the Observer's error callback if the Observable completes before any next notification was sent. If you don't want this behavior, use take(1) instead.
​​
​
​

Examples

Example 1: First value from sequence
1
// RxJS v6+
2
import { from } from 'rxjs';
3
import { first } from 'rxjs/operators';
4
​
5
const source = from([1, 2, 3, 4, 5]);
6
//no arguments, emit first value
7
const example = source.pipe(first());
8
//output: "First value: 1"
9
const subscribe = example.subscribe(val => console.log(`First value: ${val}`));
Copied!
Example 2: First value to pass predicate
1
// RxJS v6+
2
import { from } from 'rxjs';
3
import { first } from 'rxjs/operators';
4
​
5
const source = from([1, 2, 3, 4, 5]);
6
//emit first item to pass test
7
const example = source.pipe(first(num => num === 5));
8
//output: "First to pass test: 5"
9
const subscribe = example.subscribe(val =>
10
console.log(`First to pass test: ${val}`)
11
);
Copied!
Example 3: Utilizing default value
1
// RxJS v6+
2
import { from } from 'rxjs';
3
import { first } from 'rxjs/operators';
4
​
5
const source = from([1, 2, 3, 4, 5]);
6
//no value will pass, emit default
7
const example = source.pipe(first(val => val > 5, 'Nothing'));
8
//output: 'Nothing'
9
const subscribe = example.subscribe(val => console.log(val));
Copied!

Additional Resources

Last modified 1yr ago