Alexandre Annic
Alexandre Annic

Reputation: 10788

Rxjs: How to get last values when using bufferCount

Is there any way to get the latests emitted values when using bufferCount(x) when the buffer size don't reach x.

Example: the code bellow print only [0, 1]. I expect the output to include [2] after some kind of condition.

const subject = new Subject();

subject.asObservable()
  .pipe(bufferCount(2))
  .subscribe(console.log);

for(let i = 0; i < 3; i++) subject.next(i);

Upvotes: 1

Views: 1106

Answers (2)

Woon Him Wong
Woon Him Wong

Reputation: 1

you can use the takeLast operator to take the last n values emitted by the source Observable before it completes. For example:

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) // Take the last buffer
  )
  .subscribe(buffer => {
    console.log('Last buffer:', buffer);
  });

the click$ Observable emits every time the user clicks the button. We use bufferCount(5) to buffer 5 click events and emit the buffer as an array. Then we use takeLast(1) to take the last buffer emitted by the source Observable before it completes. Finally, we subscribe to the resulting Observable and log the last buffer emitted.

It will log the last buffer of 5 click events emitted before the user stopped clicking the button. Please noted if the user only clicked the button once, it will log an array containing that single-click event.

Upvotes: 0

Tadeusz Sznuk
Tadeusz Sznuk

Reputation: 1084

You need to complete the inner observable, like this:

subject.complete();

then [2] will be emitted as expected.

Upvotes: 3

Related Questions