π‘ The counterpart to last is first!
ββββ
Example 1: Last value in sequence
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+import { from } from 'rxjs';import { last } from 'rxjs/operators';βconst source = from([1, 2, 3, 4, 5]);//no arguments, emit last valueconst example = source.pipe(last());//output: "Last value: 5"const subscribe = example.subscribe(val => console.log(`Last value: ${val}`));
Example 2: Last value to pass predicate
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+import { from } from 'rxjs';import { last } from 'rxjs/operators';βconst source = from([1, 2, 3, 4, 5]);//emit last even numberconst exampleTwo = source.pipe(last(num => num % 2 === 0));//output: "Last to pass test: 4"const subscribeTwo = exampleTwo.subscribe(val =>console.log(`Last to pass test: ${val}`));
Example 3: Last with default value
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+import { from } from 'rxjs';import { last } from 'rxjs/operators';βconst source = from([1, 2, 3, 4, 5]);//no values will pass given predicate, emit defaultconst exampleTwo = source.pipe(last(v => v > 5, 'Nothing!'));//output: 'Nothing!'const subscribeTwo = exampleTwo.subscribe(val => console.log(val));
βlast π° - Official docs
βFiltering operator: takeLast, lastβ
π₯ π΅ - AndrΓ© Staltz
π Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/last.tsβ