π‘ 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.
ββββ
( example tests )
Example 1: First value from sequence
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+import { from } from 'rxjs';import { first } from 'rxjs/operators';βconst source = from([1, 2, 3, 4, 5]);//no arguments, emit first valueconst example = source.pipe(first());//output: "First value: 1"const subscribe = example.subscribe(val => console.log(`First value: ${val}`));
Example 2: First value to pass predicate
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+import { from } from 'rxjs';import { first } from 'rxjs/operators';βconst source = from([1, 2, 3, 4, 5]);//emit first item to pass testconst example = source.pipe(first(num => num === 5));//output: "First to pass test: 5"const subscribe = example.subscribe(val =>console.log(`First to pass test: ${val}`));
Example 3: Utilizing default value
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+import { from } from 'rxjs';import { first } from 'rxjs/operators';βconst source = from([1, 2, 3, 4, 5]);//no value will pass, emit defaultconst example = source.pipe(first(val => val > 5, 'Nothing'));//output: 'Nothing'const subscribe = example.subscribe(val => console.log(val));
βfirst π° - Official docs
βFiltering operator: take, first, skipβ
π₯ π΅ - AndrΓ© Staltz
π Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/first.tsβ