RAHUL KUNDU
RAHUL KUNDU

Reputation: 955

Convert Observable stream to Array

I am trying to convert an observable stream to an array, with my current approach when the count reaches to 5 then I am getting the emitted value as an array.

Is there any way to get an array of the count each time interval emits a value. Like: [0], [0, 1], [0, 1, 2] and so on.

const interval$ = interval(1000);
    interval$.pipe(
        take(5),
        toArray()
    ).subscribe({
        next: (data) => {
            // Emitting when count reaches to 5
            console.log(data);
        }
});

Upvotes: 2

Views: 512

Answers (2)

Owen Kelvin
Owen Kelvin

Reputation: 15083

You probably are looking for the scan operator

const interval$ = interval(1000);
interval$
  .pipe(
    scan((prev, next) => [...prev, next], []),
    take(5),
    tap(console.log)
  )
  .subscribe();

The above will log

[0]
[0,1]
[0,1,2]
[0,1,2,3]
[0,1,2,3,4]

See this Demo

Upvotes: 1

walki12
walki12

Reputation: 220

Use the buffercount operator to store emitted values within an array.

const interval$ = interval(1000);
    interval$.pipe(
        take(5),
        bufferCount(5)
    ).subscribe({
        next: (data) => {
            // Emitting when count reaches to 5
            console.log(data);
        }
});

Upvotes: 0

Related Questions