last

签名: last(predicate: function): Observable

根据提供的表达式,在源 observable 完成时发出它的最后一个值。


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


last - 图2

示例

示例 1: 序列中的最后一个值

( jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. import { last } 'rxjs/operators';
  3. const source = from([1, 2, 3, 4, 5]);
  4. // 没有参数则发出最后一个值
  5. const example = source.pipe(last());
  6. // 输出: "Last value: 5"
  7. const subscribe = example.subscribe(val => console.log(`Last value: ${val}`));
示例 2: 最后一个通过 predicate 函数的值

( jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. import { last } 'rxjs/operators';
  3. const source = from([1, 2, 3, 4, 5]);
  4. // 发出最后一个偶数
  5. const exampleTwo = source.pipe(last(num => num % 2 === 0));
  6. // 输出: "Last to pass test: 4"
  7. const subscribeTwo = exampleTwo.subscribe(val =>
  8. console.log(`Last to pass test: ${val}`)
  9. );
示例 3: 使用结果选择器的 last

( jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. import { last } 'rxjs/operators';
  3. const source = from([1, 2, 3, 4, 5]);
  4. // 提供第二个参数,它是一个可选的投射函数
  5. const exampleTwo = source.pipe(
  6. last(
  7. v => v > 4,
  8. v => `The highest emitted number was ${v}`
  9. )
  10. );
  11. // 输出: 'The highest emitted number was 5'
  12. const subscribeTwo = exampleTwo.subscribe(val => console.log(val));
示例 4: 使用默认值的 last

( jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. import { last } 'rxjs/operators';
  3. const source = from([1, 2, 3, 4, 5]);
  4. // 没有值通过的话则发出默认值
  5. const exampleTwo = source.pipe(last(v => v > 5, v => v, 'Nothing!'));
  6. // 输出: 'Nothing!'
  7. const subscribeTwo = exampleTwo.subscribe(val => console.log(val));

其他资源


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