Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 10 : Should I unsubscribe form subscription to valueChanges Observable in ngOnDestroy?

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 ?

like image 618
Nizar Khsib Avatar asked Dec 05 '25 03:12

Nizar Khsib


1 Answers

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();
}
like image 59
mak15 Avatar answered Dec 07 '25 18:12

mak15



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!