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?
You are looking at a bug.
If you wanted to leak memory.
Yes, it's leaking memory. The subscribe function will continue to be executed after the object referenced by
thisis destroyed. It might never happen if this object is never destroy, but it's an example of code that would fail a unit test where objects are created temporarily.Objects tagged with
@Injectable()often behave like singletons or have weak references. It might be working for a while, but once you use it in a temporary case it'll leak memory.