Reputation: 2517
How to pipe an observable data in to an array of observables and map it with another observable inside?
Consider the following observable$:
getItems$()
returning the following data:
[
{item: 1, value: 'one'},
{item: 2, value: 'two'},
{item: 3, value: 'three'},
...
]
So my question is that how to map the above observable in to a new observable such that inside it maps and unwraps another set of observables.
expected result:
[
{item: 1, value: 'one', prop: 'someValueMappedFromAnotherObservableMethod1'},
{item: 2, value: 'two', prop: 'someValueMappedFromAnotherObservableMethod2'},
{item: 3, value: 'three', prop: 'someValueMappedFromAnotherObservableMethod3'},
...
// here someValueMappedFromAnotherObservableMethod1 is the value that should be obtained as a result of flatMapping observable inside the ```items.map()``` fn.
]
This is what I;ve tried. It's not working. Its not mapping and unwrapping observables inside the items.map()
this.getItems$()
.pipe(
flatMap((items) =>
items.map((item) => ({...item, prop: this.anotherMethodReturningObservableBasedOnItemValue$(item.value))}),
),
)
.subscribe(console.log);
But the above one is not working as expected. Let me know how to do this/
I also tried this way:
this.getItems$()
.pipe(
flatMap((items) =>
merge(items.map((item) => this.anotherMethodReturningObservableBasedOnItemValue$(item.value))).pipe(
combineAll(),
),
),
)
.subscribe(console.log);
Upvotes: 2
Views: 2185
Reputation: 12071
You can achieve what you want with this:
this.getItems$()
.pipe(
mergeMap(items =>
from(items)
.pipe(
mergeMap(item =>
this.anotherMethodReturningObservableBasedOnItemValue$(item.value)
.pipe(
take(1), // toArray operator below requires all sources to complete
map(prop => ({ ...item, prop })) // Combine new prop with existing props
)
),
// Combine all items into single array
toArray()
)
)
)
.subscribe(console.log);
Upvotes: 2