Reputation: 89
How would one go about using combineLatest
with two or more arrays of observables?
const array1 = [of(1), of(2)];
const array2 = [of(3), of(4)];
combineLatest(array1, array2)
.subscribe(([array1, array2]) => {
console.log(
`array1[0]: ${array1[0]}
array1[1]: ${array1[1]}
array2[0]: ${array2[0]}
array2[1]: ${array2[1]}`
);
});
I have a stackblitz: https://stackblitz.com/edit/typescript-cnzvlo?file=index.ts&devtoolsheight=100
Upvotes: 1
Views: 4401
Reputation: 6716
The combineLatest
function expects an array of Observable
(s), not an array of array of Observable
.
So what do you have to do is:
Observable
, to an Observable
, by combining the inner Observable
(s) of each one of them using concat
function.toArray
operator.You can do something like the following:
import { combineLatest, of, concat } from 'rxjs';
import { toArray } from 'rxjs/operators';
const array1 = [of(1), of(2)];
const array2 = [of(3), of(4)];
combineLatest([
concat(...array1).pipe(toArray()),
concat(...array2).pipe(toArray()),
]).subscribe(([array1, array2]) => {
console.log(
`array1[0]: ${array1[0]}
array1[1]: ${array1[1]}
array2[0]: ${array2[0]}
array2[1]: ${array2[1]}`
);
});
And here is the working version of your StackBlitz: https://stackblitz.com/edit/typescript-3imea6?file=index.ts
Upvotes: 1