Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I unsubscribe from Angular Form changes?

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.

like image 320
Jack Avatar asked Jun 26 '18 14:06

Jack


People also ask

What happens if we don't unsubscribe in Angular?

🎩 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…

Why should we unsubscribe in Angular?

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.

Should you unsubscribe from form Valuechanges?

You must unsubscribe to prevent memory leaks and to avoid unexpected side-effects in your application.

Do I need to unsubscribe from subject Angular?

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.


1 Answers

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

like image 118
Eduardo Vargas Avatar answered Oct 23 '22 23:10

Eduardo Vargas