To prevent memory leaks caused by Observables inside Components, I always use the takeUntil()
operator before subscribing.
Here is an example of how I implement it in my components:
private stop$ = new Subject();
ngOnInit(): void {
this.http
.get('test')
.pipe(takeUntil(this.stop$))
.subscribe((data) => console.log(data));
}
ngOnDestroy(): void {
this.stop$.next();
this.stop$.complete();
}
Now, my question arises:
Do I need to call this.stop$.complete();
after next();
, or is next();
sufficient?
Will stop$
be automatically handled by the garbage collector if I don't call complete();
?
I am seeking clarification on whether it makes a difference or not. I want to ensure there are no memory leaks in my components.