I understand that I must unsubscribe certains Observable (ie: Observables that have infinite value) when Components are destroyed in order to prevent memory leaks. I do not need to do that for finite Observables as they will complete and automatically unsubscribe
.
But if I create an infinite Observable
in my component (for example FormGroup.valueChanges
, or QueryList.changes
), this one will be destroyed with the component that contains it, so I think that they will be no memory leak even if I do not unsubscribe from it.
Here is a simple example:
@Component({})
export class DummyComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
firstName: [''],
lastName: ['']
});
this.form.valueChanges.subscribe(
x => console.log(x)
);
}
}
Here, I do not unsubscribe
from this.form.valueChanges
; when my component is destroyed, the this.form.valueChanges
will be destroyed too.
Will there be a memory leak in this case?
As you probably know when you subscribe to an observable or event in JavaScript, you usually need to unsubscribe at a certain point to release memory in the system. Otherwise, you will have a memory leak. A memory leak occurs when a section of memory that is no longer being…
The RxJS first() operator waits until the first value is emitted from an observable and then automatically unsubscribes, so there is no need to explicitly unsubscribe from the subscription.
You don't need to unsubscribe from observable created by Http or HttpClient because it is finite observable (value will be emitted only once and complete will be called). However, you CAN unsubscribe from the observable created by HttpClient to cancel the request.
Remember, observables are lazy. If you don't subscribe nothing is going to happen. It's good to know that when you subscribe to an observer, each call of subscribe() will trigger it's own independent execution for that given observer. Subscribe calls are not shared among multiple subscribers to the same observable.
As Babar had mention, you need to do the unsubscribe in order to stop those subscriptions to continue watching for changes.
For your particular case I think that you have a point.
One thing I do when I have a lot of subscriptions in the same component is the following.
First I create "subscriptions", an empty Array of Subscription type.
private subscriptions: Subscription[] = [];
Then every time I need to do subscribe I push it into the array
this.subscriptions.push(this.form.valueChanges.subscribe(x => console.log(x)));
And in the ngOnDestroy I unsubscribe to every subscription inside the array.
ngOnDestroy(): void {
this.subscriptions.forEach((elem) => { elem.unsubscribe(); })
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With