wgf4242
wgf4242

Reputation: 831

angular rxjs do something after all observable sended without subscribe

I'll use async pipe, will not run subscribe method.

Like concat 1 to 10 and slice every 3 number to a new array.

import { timer, concat, interval, range } from 'rxjs';
import { delay, map, tap, take, startWith } from 'rxjs/operators';

const sliceEveryN = (a,b) => console.log('Method runs')
const arr = []
const source = range(1, 5); // [1..5]
const source2 = range(6, 5); // [6..10]
const final = concat(source, source2).pipe(
	map(v => arr.push(v))
	).pipe(
	// I want to this at last, not every observable sent
	map(v => sliceEveryN(3, v)) // [[1,2,3], [4,5,6], [7,8,9], [10]]
	)

This will run the sliceEveryN method ten times, expect once.

Upvotes: 1

Views: 431

Answers (1)

Alon Yampolski
Alon Yampolski

Reputation: 849

Using bufferCount(N) will buffer N emitions and emit and aggregated array:

Collect emitted values until provided number is fulfilled, emit as array

const final = concat(source, source2).pipe(
    tap(v => arr.push(v)),
    bufferCount(3),
    tap(v => console.log(v))
);

This will emit an array of every 3 values and print them to console.

Upvotes: 1

Related Questions