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?

Shlok Nangia
  • 2,355
  • 3
  • 16
  • 24
  • 1
    Does this answer your question? [How can I avoid multiple nested subscriptions using RxJS operators?](https://stackoverflow.com/questions/55416011/how-can-i-avoid-multiple-nested-subscriptions-using-rxjs-operators) – Tal Ohana May 04 '20 at 10:42
  • 1
    what is your use-case for this multiple subscription here? as per that you can choose your rxjs operator. – Developer May 04 '20 at 10:46
  • @Tal Ohana Nope. There are not related subscriptions. I need data from 1st subscription in second and last. –  May 04 '20 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. –  May 04 '20 at 10:50

1 Answers1

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.

Jesse
  • 2,391
  • 14
  • 15
  • 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. –  May 06 '20 at 08:01