RxJS: Take in batches of 10 until outer observable completes?

Viewed 180

Haven't touched RxJs for a while :-(

I can't figure out how to take values in batches of 10, anybody can help ?

For example

import { interval } from 'rxjs';
import { toArray, take, tap } from 'rxjs/operators';

interval(100)
  .pipe(
    take(10),
    tap(item => {
       // Should receive 10 x 10 items which would equal 100 
    })
  )
  .subscribe(console.log);

Trying to do so batch, the above is an example of a simplified version of what I am trying to acheive. Basically, the tap should receive 10 items at a time until there is no more.

Currently, the tap receives 10 items, 1 by 1, so I was thinking of using a toArray (anything better ? ) - but this doesn't help me with continuing after the 10 has been received.

What am I missing?

Thanks in advance

1 Answers

You need to use bufferCount operator

import { interval } from 'rxjs';
import { bufferCount, take, tap } from 'rxjs/operators';

interval(100)
  .pipe(
    bufferCount(10)
    tap(items => {
       console.log(items);
       // will print array of 10 items , ten times
    })
  )
  .subscribe();

Related