last

signature: last(predicate: function): Observable

Emit the last value emitted from source on completion, based on provided expression.


:bulb: The counterpart to last is first!


last - 图2

Examples

Example 1: Last value in sequence

( jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. import { last } 'rxjs/operators';
  3. const source = from([1, 2, 3, 4, 5]);
  4. //no arguments, emit last value
  5. const example = source.pipe(last());
  6. //output: "Last value: 5"
  7. const subscribe = example.subscribe(val => console.log(`Last value: ${val}`));
Example 2: Last value to pass 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. //emit last even number
  5. const exampleTwo = source.pipe(last(num => num % 2 === 0));
  6. //output: "Last to pass test: 4"
  7. const subscribeTwo = exampleTwo.subscribe(val =>
  8. console.log(`Last to pass test: ${val}`)
  9. );
Example 3: Last with result selector

( jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. import { last } 'rxjs/operators';
  3. const source = from([1, 2, 3, 4, 5]);
  4. //supply an option projection function for the second parameter
  5. const exampleTwo = source.pipe(
  6. last(
  7. v => v > 4,
  8. v => `The highest emitted number was ${v}`
  9. )
  10. );
  11. //output: 'The highest emitted number was 5'
  12. const subscribeTwo = exampleTwo.subscribe(val => console.log(val));
Example 4: Last with default value

( jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. import { last } 'rxjs/operators';
  3. const source = from([1, 2, 3, 4, 5]);
  4. //no values will pass given predicate, emit default
  5. const exampleTwo = source.pipe(last(v => v > 5, v => v, 'Nothing!'));
  6. //output: 'Nothing!'
  7. const subscribeTwo = exampleTwo.subscribe(val => console.log(val));

Additional Resources


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