When looking at code examples, I often see the case where observables inside services are not unsubscribed from.
Here is an example:
export class AuthGuard implements CanActivate {
private isLoggedIn: boolean;
private isLoggedIn$: Observable<boolean>;
constructor(private authService: AuthService, private router: Router) {
this.isLoggedIn$ = this.authService.isLoggedIn();
this.isLoggedIn$.subscribe(res => {
if (res) {
this.isLoggedIn = true;
}
else {
this.isLoggedIn = false;
}
});
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.isLoggedIn) {
return true;
}
else {
this.router.navigate(['login']);
return false;
}
}
}
Is there a reason why you would not unsubscribe from the observable this.isLoggedIn$ in this case? Or is the above example just bad coding leading to memory leaks?