[RxJS] Filtering operators: takeLast, last

时间:2022-08-22 14:18:44

Operators take(), skip(), and first() all refer to values emitted in the beginning of an Observable execution. In this lesson we will see similar operators which refer instead to the end of an Observable execution, such as takeLast().

takeLast(number): takeLast requires the source has completion.

var foo = Rx.Observable.range(1,7);

/*
--0--1--2--3--4--5--6--7-|
takeLast(2)
---------------------------(67|)
*/ var bar = foo.takeLast(2); bar.subscribe(
function (x) { console.log('next ' + x); },
function (err) { console.log('error ' + err); },
function () { console.log('done'); },
); /*
"next 6"
"next 7"
"done"
*/

If replace range() to interval(1000).take(7); then we will wait 7 seconds before the result comes out sync.

last():

var foo = Rx.Observable.range(1,7);

/*
--0--1--2--3--4--5--6--7-|
last()
---------------------------(7|)
*/ var bar = foo.last(); bar.subscribe(
function (x) { console.log('next ' + x); },
function (err) { console.log('error ' + err); },
function () { console.log('done'); },
); /*
"next 7"
"done"
*/