first
函数签名: first(predicate: function, select: function)
发出第一个值或第一个通过给定表达式的值。
与 first 对应的操作符是 last!
示例
( example tests )
示例 1: 序列中的第一个值
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+
import { from } from 'rxjs';
import { first } from 'rxjs/operators';
const source = from([1, 2, 3, 4, 5]);
// 没有参数则发出第一个值
const example = source.pipe(first());
// 输出: "First value: 1"
const subscribe = example.subscribe(val => console.log(`First value: ${val}`));
示例 2: 第一个通过 predicate 函数的值
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+
import { from } from 'rxjs';
import { first } from 'rxjs/operators';
const source = from([1, 2, 3, 4, 5]);
// 发出通过测试的第一项
const example = source.pipe(first(num => num === 5));
// 输出: "First to pass test: 5"
const subscribe = example.subscribe(val =>
console.log(`First to pass test: ${val}`)
);
示例 3: 使用可选的 projection 函数
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+
import { from } from 'rxjs';
import { first } from 'rxjs/operators';
const source = from([1, 2, 3, 4, 5]);
// 没有值通过的话则发出默认值
const example = source.pipe(first(val => val > 5, 'Nothing'));
// 输出: 'Nothing'
const subscribe = example.subscribe(val => console.log(val));
其他资源
- first - 官方文档
- 过滤操作符: take, first, skip - André Staltz
源码: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/first.ts