This is the sample code using rxjs operator, I want to print/get the second last value.
typescript
import { from } from 'rxjs';
import { map, last } from 'rxjs/operators';
//emit (1,2,3,4,5)
const source = from([1, 2, 3, 4, 5]);
//add 10 to each value
const example = source.pipe(map(val => val + 10)).pipe(last());
//output: 11,12,13,14,15
const subscribe = example.subscribe(val => console.log(val));
Currently it prints 15 but I want it to print 14 instead.
You can make use of the takeLast() and skipLast RxJS operator.
The takeLast() operator allows you to
Emits only the last
countvalues emitted by the source Observable.
while the skipLast() operator
Skip the last
countvalues emitted by the source Observable.
Now, we can combine both pipeable operators such that we will take the last 2 counts, and skip the last count.
import { range, from } from 'rxjs';
import { takeLast, map, skipLast} from 'rxjs/operators';
const source = from([1, 2, 3, 4, 5]);
const example = source
.pipe(
map(val => val + 10),
takeLast(2),
skipLast(1)
);
example.subscribe(res => console.log(res));
Here is a demo.
You can use the pairwise operator: https://www.learnrxjs.io/operators/combination/pairwise.html
import { from } from 'rxjs';
import { map,last } from 'rxjs/operators';
//emit (1,2,3,4,5)
const source = from([1, 2, 3, 4, 5]);
//add 10 to each value
const example = source.pipe(map(val => val + 10)).pipe(pairwise(),last());
//output: 11,12,13,14,15
const subscribe = example.subscribe(val => console.log(val[0]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With