Utilize the takeLast operator to capture the final n values sent by the original Observable before it finishes.
For instance:
import { fromEvent } from 'rxjs';
import { bufferCount, takeLast } from 'rxjs/operators';
const button = document.querySelector('button');
const click$ = fromEvent(button, 'click');
click$
.pipe(
bufferCount(5), // Buffer 5 clicks
takeLast(1) // Capture the last buffer
)
.subscribe(buffer => {
console.log('Last buffer:', buffer);
});
The click$ Observable triggers with each user click on the button. By using bufferCount(5), we store 5 click events and send them as an array. Subsequently, takeLast(1) selects the final recorded buffer just before completion of the source Observable. Upon subscribing to this resultant Observable, the last emitted buffer is logged.
This will display the last set of 5 consecutive click events prior to the user ceasing to click the button. It's essential to note that if the user only clicked once, a single-click event array will be logged.