Reputation: 400
Here I want to combine values from observables. This code works, but nesting subscribes in such fashion is not good. I'm looking for better solutions. Thanks in advance.
someObservable().subscribe(
data => { // array of elements
data.forEach(
element => {
anotherObservable(element.id)
.subscribe(
anotherData => doSomething(data, anotherData); // both data needed
);
}
);
}
);
Upvotes: 0
Views: 560
Reputation: 528
You can use merge for it
Click here for Official Doc
Eg:-
// RxJS v6+
import { mapTo } from 'rxjs/operators';
import { interval, merge } from 'rxjs';
//emit every 2.5 seconds
const first = interval(2500);
//emit every 2 seconds
const second = interval(2000);
//emit every 1.5 seconds
const third = interval(1500);
//emit every 1 second
const fourth = interval(1000);
//emit outputs from one observable
const example = merge(
first.pipe(mapTo('FIRST!')),
second.pipe(mapTo('SECOND!')),
third.pipe(mapTo('THIRD')),
fourth.pipe(mapTo('FOURTH'))
);
//output: "FOURTH", "THIRD", "SECOND!", "FOURTH", "FIRST!", "THIRD", "FOURTH"
const subscribe = example.subscribe(val => console.log(val));
Upvotes: 1
Reputation: 22213
You can use mergeMap for it
Like this:
return this.someObservable().pipe(
mergeMap(element=> this.anotherObservable(element.id).pipe(
map(anotherData => {
return {
res1: element ,
res2: anotherData
}
})
))
)
Upvotes: 2