I have 2 observables that are streaming data as a result of a database query, the amount of data each emits is variable and can be different to the other one. I'm trying to work out how I can combine them both so I can use a single subscription and push the emitted values into two different arrays, e.g.
let firstArray = [];
let secondArray = [];
const subscription = zip(firstObservable, secondObservable)
.subscribe({
next([first, second]) {
firstArray.push(first);
secondArray.push(second);
},
error(err) {
console.log(err);
},
complete() {
console.log(firstArray);
console.log(secondArray);
}
});
The problem with this example is that using zip causes them to only capture emitted values from the shortest observable, so if firstObservable is emitting 2 values and secondObservable is emitting 10, on complete both arrays will be of length 2. I apologise if the question is ambiguous at all, I'm quite new to using observables and am struggling to entirely grasp them. Any help would be greatly appreciated.
You can use toArray to collect all of the emitted items into an array, and forkJoin to wait for both observables to finish:
import { of, forkJoin } from 'rxjs';
import { toArray } from 'rxjs/operators';
const o1 = of(1,2,3,4,5);
const o2 = of('a', 'b');
forkJoin([
o1.pipe(toArray()),
o2.pipe(toArray())
]).subscribe(console.log);