first

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

Emit the first value or first to pass provided expression.


:bulb: The counterpart to first is last!


first - 图2

Examples

(
example tests
)

Example 1: First value from sequence

( jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. import { first } from 'rxjs/operators';
  3. const source = from([1, 2, 3, 4, 5]);
  4. //no arguments, emit first value
  5. const example = source.pipe(first());
  6. //output: "First value: 1"
  7. const subscribe = example.subscribe(val => console.log(`First value: ${val}`));
Example 2: First value to pass predicate

( jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. import { first } from 'rxjs/operators';
  3. const source = from([1, 2, 3, 4, 5]);
  4. //emit first item to pass test
  5. const example = source.pipe(first(num => num === 5));
  6. //output: "First to pass test: 5"
  7. const subscribe = example.subscribe(val =>
  8. console.log(`First to pass test: ${val}`)
  9. );
Example 3: Using optional projection function

( jsBin |
jsFiddle )

  1. const source = Rx.Observable.from([1, 2, 3, 4, 5]);
  2. //using optional projection function
  3. const example = source.first(
  4. num => num % 2 === 0,
  5. (result, index) => `First even: ${result} is at index: ${index}`
  6. );
  7. //output: "First even: 2 at index: 1"
  8. const subscribe = example.subscribe(val => console.log(val));
Example 4: Utilizing default value

( jsBin |
jsFiddle )

  1. const source = Rx.Observable.from([1, 2, 3, 4, 5]);
  2. //no value will pass, emit default
  3. const example = source.first(val => val > 5, val => `Value: ${val}`, 'Nothing');
  4. //output: 'Nothing'
  5. const subscribe = example.subscribe(val => console.log(val));

Additional Resources


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