'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);
}
);
Solution 1:[1]
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...
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
