0

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]

2 Answers 2

1

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)
  • an Array is treated as an Observable since it actually can represent a stream of data, which is what an Observable is
Sign up to request clarification or add additional context in comments.

Comments

0

+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));
})

Comments

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.