0

Got stuck on mergemap while learning rxjs. I have 2 observables

let list1= of(1,2)
let list2= of('A','B')

and I want to concatenate the results like this:

1A, 1B, 2A, 2B

How to accomplish the concatenation inside mergemap block

 return list1.pipe(
     mergeMap((item: any) => {
           i want to concatenate items of list1 with items of list2 here 
     })
 ).subscribe(console.log)

I appreciate your help with this please

I have tried

 return list1.pipe(
     mergeMap((item: any) => {
           return item + list2  
     })
 ).subscribe(console.log)

But it returns 1 [ o b j e c t ] 2 [ o b j e c t ]

1 Answers1

2

Use an inner pipe

import { of, map, mergeMap } from 'rxjs';

const list1 = of(1, 2);
const list2 = of('A', 'B');

list1
  .pipe(
    mergeMap((list1Value) =>
      list2.pipe(map((list2Value) => list1Value + list2Value))
    )
  )
  .subscribe(console.log);

Stackblitz: https://stackblitz.com/edit/rxjs-2zsk7b?file=index.ts

MoxxiManagarm
  • 8,735
  • 3
  • 14
  • 43
  • Thanks for your kind response, But i am getting error, Argument of type '(list1Value: number) => void' is not assignable to parameter of type '(value: number, index: number) => ObservableInput', i have also tried with mergeMap((list1Value: any), but same error – Samit Sinha Dec 12 '22 at 09:56
  • 1
    @SamitSinha The shown code works well. It looks like you forgot a `return` somewhere. When you use array functions with a function body, i.e. `() => { ... }` you need to use `return`, i.e. `(list1Value) => { return list2.pipe(...); }`. However, the shorthand proposed in the answer looks better. – Lukas-T Dec 12 '22 at 10:04
  • 1
    Yes, you are right. My bad, I have indeed missed the return inside the map block. Thanks much @MoxxiManagarm for the help – Samit Sinha Dec 12 '22 at 12:57