1

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?

4
  • 1
    Does this answer your question? How can I avoid multiple nested subscriptions using RxJS operators? Commented May 4, 2020 at 10:42
  • 1
    what is your use-case for this multiple subscription here? as per that you can choose your rxjs operator. Commented May 4, 2020 at 10:46
  • @Tal Ohana Nope. There are not related subscriptions. I need data from 1st subscription in second and last. Commented May 4, 2020 at 10:49
  • @GaurangDhorda I need dispatch action, and for it need some different data. But also those selectors should be reloaded when change select user in Dropdown. That's why I need nested subscription - aut. refresh. Commented May 4, 2020 at 10:50

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your response. But I need solution in pure rxjs, no double selector etc. I should use multiple switchMap or what? I tried mixed solution, but without success.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.