Tsafou
Tsafou

Reputation: 53

RxJs Observables nested subscriptions with takeUntil

How am I supposed to get rid of these nested subscriptions? I thought to do that using concatMap or mergeMap - if you agree, how to I handle the takeUntil for inner subscriptions being different than the outer one? I am quite new to operators and RxJs.

this.myService.selectedCustomerId
.pipe(
    takeUntil(this.unsubscribe),
).subscribe((customerId: number) => {
    // Do some stuff...

    this.anotherService.hasPermission("ROLE1", customerId).pipe(
        takeUntil(this.cancel),
    ).subscribe(hasPermission => this.hasPermissionForRole1 = hasPermission);

    this.anotherService.hasPermission("ROLE2", customerId).pipe(
        takeUntil(this.cancel),
    ).subscribe(hasPermission => this.hasPermissionForRole2 = hasPermission);

    this.anotherService.hasPermission("ROLE3", customerId).pipe(
        takeUntil(this.cancel),
    ).subscribe(hasPermission => this.hasPermissionForRole3 = hasPermission);
  }
);

Upvotes: 2

Views: 979

Answers (1)

gil
gil

Reputation: 2552

you can achieve it this way:

this.myService.selectedCustomerId
    .pipe(
        takeUntil(this.unsubscribe),
        mergeMap(customerId: number) => {
            const roles = ["ROLE1", "ROLE2", "ROLE3"];
            return forkJoin(
                roles.map(role => this.anotherService.hasPermission(role, customerId))
            )
        }
    ).subscribe(([role1, role2, role3]) => {
        // Do some stuff...
        
    }

Upvotes: 5

Related Questions