When subscribing to changes in an Angular Abstract Control using valueChanges, is it necessary to unsubscribe()
?
I often do this:
// this.form is a FormGroup within a Component.
this.form.valueChanges.subscribe(_ => {
console.log(this.form.value);
});
But should I be managing the subscription myself (as I do with ngrx
in general)?:
import { Subscription } from 'rxjs';
// this.subscription is ngrx Subscription.
this.subscription = this.form.valueChanges.subscribe(_ => {
console.log(this.form.value);
});
public ngOnDestroy() {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
The only reason I have not done this previously is because tutorials, examples and documentation on Angular Forms generally omit storing a reference to the subscription, and instead, just use valueChanges as is.
Conversely, ngrx tutorials seem to highlight the importance of unsubscribing to avoid memory leaks.
🎩 Automagically Unsubscribe in Angular 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…
In Angular applications, it's always recommended to unsubscribe the observables to gain benefits like: Avoids Memory Leaks. Aborting HTTP requests to avoid unwanted calls.
You must unsubscribe to prevent memory leaks and to avoid unexpected side-effects in your application.
Also, you don't need to unsubscribe from Observables that you subscribe to in the AppComponent , as it never gets destroyed. You always have to unsubscribe from: Any Observable or Subject you created manually.
Yes it is necessary, but you could use take until instead.
private unsubscribe$: Subject<void> = new Subject<void>();
this.subscription = control.valueChanges
pipe(takeUntil(this.unsubscribe$))
.subscribe(_ => {
console.log(this.form.value);
});
ngOnDestroy() {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87
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