Angular 6 pipe RxJs operator to chain 3 dependant observables
To chain observables, you can use the flatMap
function. This function is like promises then, meaning the function is only executed once the observable has resolved to a value.
There is also an observable function called forkJoin
which allows you to wait for multiple async requests to all have resolved to a value.
Example:
getUsers().flatMap((users) => {
// the users variable is the list of users
var multipleObservables = [];
users.forEach((u) => {
multipleObservables.push(
getUserAddresses(u.id).map((usersAddresses) => {
u.addresses = usersAddresses;
return u;
});
);
});
return forkJoin(multipleObservables);
}).flatMap((usersWithAddresses) => {
// the usersWithAddresses variable is an array of users which also have their addresses
var multipleObservables = [];
usersWithAddresses.forEach((u) => {
multipleObservables.push(
getUserCompanies(u.id).map((usersCompanies) => {
u.companies = usersCompanies;
return u;
});
);
});
return forkJoin(multipleObservables);
});
You can write something like this to chain you request and grow your user objects.
Something like this could work
getUsers()
.pipe(
switchMap(users => from(users)),
mergeMap(user => forkJoin(getAddresses(user.id), getCompanies(user.id))
.pipe(map(data => ({user, addresses: data[0], companies: data[1] })))
tap(data => data.user.addresses = data.addresses),
tap(data => data.user.companies = data.companies),
map(data => data.user),
toArray()
)
)
Applied to a different use case a similar chain is explained in more details here.