Jack
Jack

Reputation: 10613

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.

Upvotes: 9

Views: 4821

Answers (1)

Eduardo Vargas
Eduardo Vargas

Reputation: 9392

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

Upvotes: 7

Related Questions