- first
- 签名:
first(predicate: function, select: function)
- 签名:
- 发出第一个值或第一个通过给定表达式的值。
- 示例
- 示例 1: 序列中的第一个值
- 示例 2: 第一个通过 predicate 函数的值
- 示例 3: 使用可选的 projection 函数
- 示例 4: 利用默认值
- 示例
- 其他资源
first
签名: first(predicate: function, select: function)
发出第一个值或第一个通过给定表达式的值。
与 first 对应的操作符是 last!

示例
(
example tests
)
示例 1: 序列中的第一个值
( jsBin |
jsFiddle )
import { from } from 'rxjs/observable/from';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 函数的值
( jsBin |
jsFiddle )
import { from } from 'rxjs/observable/from';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 函数
( jsBin |
jsFiddle )
const source = Rx.Observable.from([1, 2, 3, 4, 5]);// 使用可选的 projection 函数const example = source.first(num => num % 2 === 0,(result, index) => `First even: ${result} is at index: ${index}`);// 输出: "First even: 2 at index: 1"const subscribe = example.subscribe(val => console.log(val));
示例 4: 利用默认值
( jsBin |
jsFiddle )
const source = Rx.Observable.from([1, 2, 3, 4, 5]);// 没有值通过的话则发出默认值const example = source.first(val => val > 5, val => `Value: ${val}`, '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
