I am curious about a better way to write the following scenario.
Assume I have a userObservable fetches user data (user) from db then I'd like to
- Validate some input with
user,validateObservable - After get some external data with
user,getExternalObservable - After combine externalData with
userand update db again,updateDbObservable - In the end I'd like to get this updated user data.
Normally I can do this as below, but this code looks repetitive and produces a little bit ugly map -> forkJoin -> mergeAll boilerplate.
userObservable.pipe(
map((user) => {
return forkJoin({
user: of(user),
verifyResult: verifyObservable(user)
});
},
mergeAll(),
map(({ user }) => {
return forkJoin({
user: of(user),
externalData : getExternalObservable(user)
});
}),
mergeAll(),
map(({user, externalData}) => {
return updateDbObservable(user, externalData);
}),
mergeAll(),
);
Thank you !
You can greatly simplify your code by doing the following:
verifiedUserobservable that only emits when verification passesHere we declare an observable that will emit the user only when verification passes.
Here we add a
.pipe()to each observable inside theswitchMap:When
verifiedUseremits, the results flow togetExternalObservable(), then finally theupdateDbObservable().Notice that the most inner call has access to all prior emitted values so there's no need to fabricate an object using
forkJoin/of.Separate Observables
In the above code we've defined separate smaller observables that can make it easier to follow the logic. If we need to alter what it means to be a "verified user", we don't need to change our
updateDbResultobservable at all!