Following the comments of yurzui I conclude the following:
Despite the service being destroyed (as it was provided in the component that got destroyed) the observable and subscription continue to work outside the service and component. I assume this doesn't get collected at some point, so I explicitly clean it up.
My question was not how to unsubscribe from the observable, but regardless I thought it would be useful to share my actual solution to managing the subscriptions I had expected to be destroyed. I created a destroy()
function on the service which the parent component calls in the ngOnDestroy
cycle. In this function I emit complete from all infinite observables in the service. This saves me from repeating myself and unsubscribing in all the child components.
In my service:
private subject = new BehaviorSubject<string>(null);
public testObservable(): Observable<string> {
// ...
this.subject.next('result');
return this.subject.asObservable();
}
destroy() {
this.subject.complete();
}
In my component:
ngOnInit() {
this.testService.testObservable().subscribe(data => console.log(data));
}
ngOnDestroy() {
this.testService.destroy();
}
Edit
I have included a working stackblitz in case there is some uncertainty about what my solution is: https://stackblitz.com/edit/destroyservice. What I like about it is that I unsubscribe from 6 subscriptions with 3 lines of code, and I don't need to include ngOnDestroy in any of the child components.