I have this scenario in typescript/angular with rxjs 6.5:
main(){
const properties = ['session', 'user'];
const source: Observable<any> = from(properties);
source
.pipe(
mergeMap(key => this.getKey().map((value) => ({key: key, value: value}))),
tap((result) => {
// sending the result elsewhere;
}),
).subscribe(
(result) => {
console.log('Final result ->', result);
}
);
console.log('\n');
}
getKey(): Observable<any> {
// Mock function that returns an observable that emits 1 value
const observable = from(['test']);
return observable;
}
The output is:
Final result -> {key: "session", value: "test"}
Final result -> {key: "user", value: "test"}
1st question: How do I return, in the most elegant way, upon subscription on source, just 1 value, with the combined results of the inner observables?
My wanted output, with the subscription in this way (because I want this combined operation to be in the pipe), would be:
(...).subscribe(
(result) => {console.log('Final Result:', result}
)
OUTPUT:
Final result -> [{key: "session", value: "test"}, {key: "user", value: "test"}]
2nd question If I don't care about the result of the inner observables, how do I return just 1 value or how do I know when all the inner observables have been completed?
Thanks in advance.
To get combined result of all response of mergeMap, you can also try like this:
return this.request1().pipe(
mergeMap(res1=> this.request2(res1.id).pipe(
map(res2=> {
return {
res1: res1,
res2: res2
}
})
))
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With