Demo: takeLast
The takeLast is a filter operator that emits only the last N items from source, after waiting for the source to complete.
takeLast( lastNItems)
//source emits 6 items
const source = timer(500, 500).pipe(take(6));
//fiter to emit the last 3 items
const filterItems = takeLast(3);
//emits items with intervals of 1sec, to remove the overlap
const emitWithTimeGap = concatMap(v => of(v).pipe(delay(1000)));
const output = source.pipe( filterItems , emitWithTimeGap)
.subscribe(v=>console.log(v))
The filter operator "takeLast", enables us to emit only the last N items from the source.
Let's see how it works through the demo. The source will emit 6 items, from 0 to 5. But, if we are interested in only in the last 3 items, we can use take Last(3) as our filter.
The takeLast always waits until the source input completes: - Keeping only the last 3 input from source in it's buffer, discarding the rest of the items.
As soon as it gets a complete notification from the source: - It immediately emits the 3 buffered items into the output stream.
To show them distinctly on our timescale, we are separating them with the "emit With Time Gap" operator.
- A custom operator built using concatMap and delay.
As the output shows, "take Last (3)" has emitted only the last 3 items:
- 3, 4 & 5.