Reputation: 1966
I am using forkJoin to subscribe multiple inner observable. How can I flat nested array to single level array.
const x$ = of([1, 2, 3, 4]);
const y$ = of([2, 4]);
x$.pipe(
switchMap((t) => {
const innerArr$ = t.map((z) => y$.pipe(map((_) => _.map((y) => y * z))));
return forkJoin(innerArr$);
})
).subscribe(console.log);
Playground Link: Rxjs stackblitz
Expected Output:
[2,4,4,8,6,12,8,16]
Upvotes: 0
Views: 1352
Reputation: 30088
+1 to the answer by @Picci if you want a stream of numbers.
If you want to wind up with a single array instead, you can flatten the result in the subscription:
x$.pipe(
switchMap((t) => {
const innerArr$ = t.map((z) => y$.pipe(map((_) => _.map((y) => y * z))));
return forkJoin(innerArr$);
})
)
.subscribe((res) => {
console.log([].concat.apply([], res));
})
Upvotes: 0
Reputation: 17752
You can try this
x$.pipe(
switchMap((t) => {
const innerArr$ = t.map((z) => y$.pipe(map((_) => _.map((y) => y * z))));
return forkJoin(innerArr$);
}),
mergeMap((aa) => from(aa).pipe(mergeMap((a) => a)))
).subscribe(console.log);
The key here is
mergeMap
is actually a flatten Observable-like objects (actually
mergeMap
was formerly known as flatMap
)Upvotes: 1