0

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?

4
  • It depends if you want to wait until they both complete or you want to accumulate values as they arrive. What you expect to happen when you call x.next(7)? Commented Mar 27, 2018 at 16:58
  • I would want them to accumulate as received. I'd expect [1,2,3,4,5,6,7] Commented Mar 27, 2018 at 17:05
  • So sometimes you're going to push arrays like x.next([1, 2, 3]) and sometimes individual values like x.next(7)? Commented Mar 27, 2018 at 17:08
  • I see now why this is troublesome. I guess I would have access to the full array of values so I would expect x.next([1,2,3,4]) and y.next([4,5,6,7]) to emit [1,2,3,4,4,5,6,7] Commented Mar 27, 2018 at 17:10

2 Answers 2

1
Observable.combineLatest( x, y )
.map( ( [ x, y ] ) => ( [ ...x, ...y ] ) );
Sign up to request clarification or add additional context in comments.

Comments

1

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();

2 Comments

your response would be correct if I was appending to the existing array, but since I'm providing the complete array, this results in duplication
so you didn't want to accumulate values as they arrive but rather concat the two most recent values from both Observables :).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.