Skip to content

Latest commit

 

History

History
94 lines (68 loc) · 2.87 KB

first.md

File metadata and controls

94 lines (68 loc) · 2.87 KB

first

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

Emit the first value or first to pass provided expression.


💡 The counterpart to first is last!


Examples

( example tests )

Example 1: First value from sequence

( jsBin | jsFiddle )

import { from } from 'rxjs/observable/from';
import { first } from 'rxjs/operators';

const source = from([1, 2, 3, 4, 5]);
//no arguments, emit first value
const 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

( jsBin | jsFiddle )

import { from } from 'rxjs/observable/from';
import { first } from 'rxjs/operators';

const source = from([1, 2, 3, 4, 5]);
//emit first item to pass test
const 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: Using optional projection function

( jsBin | jsFiddle )

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

( jsBin | jsFiddle )

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

Additional Resources


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