I've been looking around for a simple way to avoid the memory leaks I've read about caused by failing to unsubscribe. Most of the time I'm just wanting the ONE response from my backend. And then I'll want to unsubscribe. So why not call it in the callback?
onSubmit(){
var subscription = this.puzzleService.login(this.nameoremail, this.password).subscribe( success =>{
if(success){
this.router.navigate(['/puzzles']);
}
else{
this.message="Login failed. Please try again.";
}
this.loading=false;
subscription.unsubscribe();
});
this.loading=true;
}
Note the assignment of the subscription to a local variable. This local variable is then locked inside a closure and told to unsubscribe when its work is done. No class variables, no takeUntil, nothing else.
It compiles and runs without error. I'm not familiar enough with the debugger to determine if the observable object is actually destroyed and subsequently garbage collected.
Is there something I'm missing? Can someone more familiar with the debugger correct me? Because if this works I'm going to be doing this everywhere. Except in my pollWords() function...
This seems much simpler than other solutions I've seen advocated. I'd think I didn't even really need the closure, as when I look at it in the debugger I see "_this" is the closure for "this" and "this" is actually the observable. So if there was some way to prevent the munging that is happening to "this" then I could call "this.unsubscribe()" and be done. Not that an object reference closure is a horrible thing...
References: