Home > Mobile >  subscribe to array of nested Observables
subscribe to array of nested Observables

Time:07-08

I have array containing objects each object has two props one of it is a observable value

let myArray = [{def: 'name1', value: EventEmitter_}, {def: 'name2', value: EventEmitter_}]

What im trying to do is subscribe to the Observables and and return the root Object where the change occurred

so far I only get the specific value

      myArray.forEach(e => {
        e.value.subscribe(e => console.log(e))
      })

I tried using merge

  merge(myArray).subscribe((v)=> {
        console.log(v)
       })

but that does not work if the Observable is nested

CodePudding user response:

You could pipe the value stream.

myArray.forEach(e => {
  e.value.pipe(
    map(v => [e.def, v]),
  ).subscribe(([d, v]) => console.log(`Root ${d} returned %{v}`));
})

CodePudding user response:

obs = merge(
    ...this.array.map((x: any) =>
      x.value.pipe(map((res) => ({ def: x.def, response: res })))
    )
  );

You merge the "observables" transformed with a property "def", and a property "response". So you only need one subscripcion

See stackblitz

  • Related