Reputation:
I would like to transform below code snippet:
this.dataUserSubscription = this.store$.pipe(select(selectUser)).subscribe(
user => {
this.store$.pipe(select(selectUserData, {user}), take(1))
.subscribe(userData => {
if (userData === null) {
this.store$.pipe(select(selectUserManagement, {user}), take(1)).subscribe(
userManagement => {
this.store$.dispatch(saveUserDataToStore({
user,
userManagement
}));
});
}
});
by avoid nested subscription. All examples, which I found, is per two subscriptions.
this.dataUserSubscription = this.store$.pipe(select(selectUser),
switchMap(user => this.store$.pipe(select(selectUserData, {user}))))
.subscription(userData => {
// logic
})
But it is no proper solution for my example of code. Why is the proper step for fixing multiple nested subscriptions?
Upvotes: 1
Views: 453
Reputation: 2597
Per RxJS best practices, your second example is a perfectly acceptable approach.
But per NgRx best practices, you can get rid of the nested subscription by just combining your selectors.
It's hard to say exactly what to do without seeing your selector
files, but if you already have the user
in the store, then you should be able to pull the user data out of the store without 2 selector calls.
Maybe something like:
const getDataForUser = createSelector(
selectUser,
selectUsers,
(user, userDataDictionary) => userDataDictionary[user.id]
)
Then just use the one getDataForUser
selector.
Upvotes: 1