3

I have a form like this :

this.form = this.fb.group({
  username: ["Put name"],
  address: ["Put address"]
});

And I am listening to username input value :

this.form.controls.username.valueChanges.subscribe(val =>
 //doSomething()
);

Do you think I should add a pipe(takeUntil(this.destroy$)) in order to avoid memory leaks ?

Is there a way to test if I do not unsubscribe when the component is destroyed, the Observable is still living in memory ?

Nizar Khsib
  • 90
  • 1
  • 8
  • Yes, you always should unsubscribe from your subscriptions. You can do it with pipe or just with Subscription property with usage the unsubscribe method in ngOnDestroy hook. – Anton Marinenko Apr 29 '21 at 10:10
  • To make sure you don't have any memory leaks - yes. It's a best practice. –  Apr 29 '21 at 10:11
  • Its the best practise. just implement OnDestroy and add a Subscription field. Also do the unsubscription inside the ngOnDestroy() method.\ – Rohith V Apr 29 '21 at 10:14
  • https://stackoverflow.com/questions/41364078/angular-2-does-subscribing-to-formcontrols-valuechanges-need-an-unsubscribe/46893278 answers this question – Yevhenii Dovhaniuk Apr 29 '21 at 10:15
  • Does this answer your question? [Angular 2 - Does subscribing to FormControl's valueChanges need an unsubscribe?](https://stackoverflow.com/questions/41364078/angular-2-does-subscribing-to-formcontrols-valuechanges-need-an-unsubscribe) – Owen Kelvin Apr 29 '21 at 11:11
  • Is there a way to test if I do not unsubscribe when the component is destroyed, the Observable is still living in memory ? – Nizar Khsib Apr 29 '21 at 12:38
  • You **don't have to unsubscribe** in this case. That Subject(`valueChanges`) is bound to that component and when that component is destroyed, there is no way the subscribers will ever receive any values. [Here](https://indepth.dev/posts/1433/rxjs-why-memory-leaks-occur-when-using-a-subject) you can find an article that explains why memory leaks occur. – Andrei Gătej Apr 29 '21 at 13:30

1 Answers1

-1

Instead of destroy, you could also do this

public sub: Subscription;

contructor() {
  this.sub = new Subscription();
}

this.sub.add(this.form.controls.username.valueChanges.subscribe(val =>
 //doSomething()
));

ngOnDestroy() {
   this.sub.unsubscribe();
}
mak15
  • 367
  • 2
  • 12