I have developed a basic authentication service and another component called Foo
that performs the following tasks:
- retrieve data from two lists
- use the retrieved lists to subscribe to the authentication login observable and fetch additional data
export class AuthService implements OnInit {
login: BehaviorSubject<Login | undefined> = new BehaviorSubject<Login | undefined>(undefined);
public readonly login$: Observable<Login | undefined> = this.login.asObservable();
constructor(private httpService: HttpHandlerService) { }
ngOnInit(): void {
this.httpService.login().subscribe(
(login: Login) => {
this.login.next(login);
});
}
}
export class Foo implements OnInit {
subscription?: Subscription;
listA?: KeyValuePair[];
listB?: KeyValuePair[];
constructor(private httpHandlerCached: HttpHandlerCachedService, private auth: AuthService) {
}
ngOnInit(): void {
this.initLists().subscribe(([listA, listB]) => {
this.listA = listA;
this.listB = listB;
this.initModule();
});
}
initLists(): Observable<[KeyValuePair[], KeyValuePair[]]> {
return forkJoin([
this.httpHandlerCached.getAllListA(),
this.httpHandlerCached.getAllListB()
]);
}
initModule(): void {
this.auth.login$.subscribe((login) => {
if (login) {
this.httpHandler.getSomeData(login.id)
.subscribe(someData => doSomeStuff(someData, listA, listB));
}
})
}
}
In my version:
export class Foo implements OnInit, OnDestroy {
listA?: KeyValuePair[];
listB?: KeyValuePair[];
subscription?: Subscription;
constructor(private httpHandlerCached: HttpHandlerCachedService, private auth: AuthService) { }
ngOnInit(): void {
this.subscription = this.initLists().subscribe(([listA, listB]) => {
this.listA = listA;
this.listB = listB;
this.initModule();
});
}
initLists(): Observable<[KeyValuePair[], KeyValuePair[]]> {
return forkJoin([
this.httpHandlerCached.getAllListA(),
this.httpHandlerCached.getAllListB()
]);
}
initModule(): void {
this.subscription = this.auth.login$.subscribe((login) => {
if (login) {
this.httpHandler.getSomeData(login.id)
.subscribe(someData => doSomeStuff(someData, listA, listB));
}
})
}
ngOnDestroy() {
this.subscription?.unsubscribe();
}
}
My inquiries:
- Is this the correct approach for managing both subscriptions?
- Do I need to unsubscribe in both scenarios?
Appreciate your input!