How to call something after completion of nested subscriptions in typescript/rxjs?

So I have to create some user which on succession on which I have to create 2 different entities as well. So it is something like this.

this.userRepository.saveAsNew(user).subscribe((user: User) => {
   user.addEntity1(Entity1).subscribe((entity1: EntityClass) => {},
         (err) => {
        this.isError = true;
        //show error}
         );
        user.addEntity2(entity2).subscribe(() => {},
          (err) => {
        this.isError = true;
        // do something
});
      }
    },
      (err) => {
        this.isError = true;
        // do something
      });

if (!this.Error){
//show success creation of all three entities
} 

now the problem is that since Error is defined false by default and when first subscription runs it is false and it shows success even when it is failure. So in short I want to execute this last if statement after I have gone through all the three subscriptions. I can do this with putting callback on the outer subscription but I think that over complicates this whole thing. Is there any better approach to this?

Your help will be really appreciated.

Upvotes: 0

Views: 871

Answers (1)

Barremian
Barremian

Reputation: 31125

  1. Avoid nested subscriptions. Instead you could use higher order mapping operator like switchMap to map between observables.
  2. Use RxJS forkJoin function to trigger multiple independent observables in parallel.
this.userRepository.saveAsNew(user).pipe(
  switchMap((user: User) => 
    forkJoin([                         // <-- begin `forkJoin` array
      user.addEntity1(Entity1).pipe(
        catchError((error: any) => {
          // do something on error
          return throwError(error);
        })
      ), 
      user.addEntity2(entity2).pipe(
        catchError((error: any) => {
          // do something on error
          return throwError(error);
        })
      )
    ])                                // <-- end `forkJoin` array
  )
).subscribe({
  next: (res: any) => {

  },
  error: (error: any) => {

  },
  complete: () => {
    // do something when all observables are complete
    // show success creation of all three entities
  }
});

Upvotes: 1

Related Questions