first

签名: first(predicate: function, select: function)

发出第一个值或第一个通过给定表达式的值。


:bulb: 与 first 对应的操作符是 last


first - 图2

示例

(
example tests
)

示例 1: 序列中的第一个值

( 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. // 没有参数则发出第一个值
  5. const example = source.pipe(first());
  6. // 输出: "First value: 1"
  7. const subscribe = example.subscribe(val => console.log(`First value: ${val}`));
示例 2: 第一个通过 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. // 发出通过测试的第一项
  5. const example = source.pipe(first(num => num === 5));
  6. // 输出: "First to pass test: 5"
  7. const subscribe = example.subscribe(val =>
  8. console.log(`First to pass test: ${val}`)
  9. );
示例 3: 使用可选的 projection 函数

( jsBin |
jsFiddle )

  1. const source = Rx.Observable.from([1, 2, 3, 4, 5]);
  2. // 使用可选的 projection 函数
  3. const example = source.first(
  4. num => num % 2 === 0,
  5. (result, index) => `First even: ${result} is at index: ${index}`
  6. );
  7. // 输出: "First even: 2 at index: 1"
  8. const subscribe = example.subscribe(val => console.log(val));
示例 4: 利用默认值

( jsBin |
jsFiddle )

  1. const source = Rx.Observable.from([1, 2, 3, 4, 5]);
  2. // 没有值通过的话则发出默认值
  3. const example = source.first(val => val > 5, val => `Value: ${val}`, 'Nothing');
  4. // 输出: 'Nothing'
  5. const subscribe = example.subscribe(val => console.log(val));

其他资源


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