Learn RxJS
Search…
last

signature: last(predicate: function): Observable

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

πŸ’‘ The counterpart to last is first!
​​
​
​

Examples

Example 1: Last value in sequence
1
// RxJS v6+
2
import { from } from 'rxjs';
3
import { last } from 'rxjs/operators';
4
​
5
const source = from([1, 2, 3, 4, 5]);
6
//no arguments, emit last value
7
const example = source.pipe(last());
8
//output: "Last value: 5"
9
const subscribe = example.subscribe(val => console.log(`Last value: ${val}`));
Copied!
Example 2: Last value to pass predicate
1
// RxJS v6+
2
import { from } from 'rxjs';
3
import { last } from 'rxjs/operators';
4
​
5
const source = from([1, 2, 3, 4, 5]);
6
//emit last even number
7
const exampleTwo = source.pipe(last(num => num % 2 === 0));
8
//output: "Last to pass test: 4"
9
const subscribeTwo = exampleTwo.subscribe(val =>
10
console.log(`Last to pass test: ${val}`)
11
);
Copied!
Example 3: Last with default value
1
// RxJS v6+
2
import { from } from 'rxjs';
3
import { last } from 'rxjs/operators';
4
​
5
const source = from([1, 2, 3, 4, 5]);
6
//no values will pass given predicate, emit default
7
const exampleTwo = source.pipe(last(v => v > 5, 'Nothing!'));
8
//output: 'Nothing!'
9
const subscribeTwo = exampleTwo.subscribe(val => console.log(val));
Copied!

Additional Resources