angularrxjsunsubscribe

Should I unsubscribe from observable defined in component?


I have an Angular component with observable (BehaviourSubject) set as a class member.
At some point I subscribe to it.
The question is: should I unsubscribe from it in ngOnDestroy() or not?
It's unclear since the lifetime of observable seems to be the same as a lifetime of the component and probably we shouldn't care about memory leak.

Example code:

@Component(...)
class MyComponent implements OnInit {
    public subject: BehaviorSubject<string> = new BehaviorSubject('');
    
    public ngOnInit(): void {
         this.subject.subscribe(...);
    }
}


Solution

  • See this answer: https://stackoverflow.com/a/41177163/12914833

    Basically if the observable completes, you don't need to unsubscribe. An example of this would be the observable you get from an http request.

    If it does not complete before the component is destroyed, you will cause a memory leak. An example of this would be an observable to a database that updates on change.