Jeremy Thomas
Jeremy Thomas

Reputation: 6674

Accumulate observable array values into single final array

If I have 2 Observable arrays, x$ and y$:

let x = new BehaviorSubject([1,2,3])
let y = new BehaviorSubject([4,5,6])
let x$ = x.asObservable();
let y$ = y.asObservable();

that I'd like to accumulate into a single array of values such that when subscribed to would emit [1,2,3,4,5,6], how can I achieve that?

Upvotes: 0

Views: 321

Answers (2)

error
error

Reputation: 756

Observable.combineLatest( x, y )
.map( ( [ x, y ] ) => ( [ ...x, ...y ] ) );

Upvotes: 1

martin
martin

Reputation: 96889

If it's this simple you can just use scan() to collect all values. It doesn't even matter what's the source so you can just merge the two Observables:

Observable.merge(x, y)
  .scan((acc, arr) => [...acc, ...arr], [])
  .subscribe();

Upvotes: 1

Related Questions