Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular Rxjs Manage Nested Subscriptions

Hi I’ve a function which has nested subscriptions.

  public loadUser(): Observable<string> {
    return this.getUser().subscribe(
      (userResponse: any) => {
        if (userResponse) {
          this.userId = userResponse.toLowerCase();
          this.getAppSupportUsersList();
          this.getUserEntitlements().subscribe((response: any) => {
            localStorage.setItem('UserEntitlements', JSON.stringify(response));
            this.processUIEntitlements(response);
            this.getUserDetails(this.userId).subscribe((userDetails) => {
              this.userInfo = userDetails;
              this.setUserName();
            });
          });
        }
      },
      (error) => {
        console.error(error);
      }
    );
  }

I’m not sure how can we avoid nesting of subscriptions. Is there a better way to rewrite the nested subscriptions using switchMap() or mergeMap()?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This can be re-written with a rxjs switchMap or a map, depending on how you want to handle multiple requests.

If only the latest counts, which seems to be the most indicated since you are writing to the local storage, go with the switchMap approach.

public loadUser(): Observable<string> {
  return this.getUser().pipe(
    filter(val => !!val),
    switchMap(userResponse => {
      this.userId = userResponse.toLowerCase();
      this.getAppSupportUsersList();
      return this.getUserEntitlements();
    }),
    switchMap(response => {
      localStorage.setItem('UserEntitlements', JSON.stringify(response));
      this.processUIEntitlements(response);
      return this.getUserDetails(this.userId);
  }).subscribe({
    next: (userDetails) => {
      this.userInfo = userDetails;
      this.setUserName();
    },
    error: (error) => console.log(error)
  })
}     
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading