Home > Software design >  If I use a subscribe with formControl I must unsubscribe in the ngOnDestroy?
If I use a subscribe with formControl I must unsubscribe in the ngOnDestroy?

Time:10-26

  this.typeCtrl.valueChanges.subscribe((value) => {
    if (value === 'new') {
      this.percent = '20';
    } else {
      this.percent = '10';
    }
  });

I have a subscribe with a valuechange of a formControl, should I unsubscribe or the form does it by default?

CodePudding user response:

you should unsubscribe every subscription in ngOnDestroy

private _unsubscribeAll = new Subject<void>();



this.typeCtrl.valueChanges.pipe(takeUntil(this._unsubscribeAll)).subscribe((value) => {
  if (value === 'new') {
    this.percent = '20';
  } else {
    this.percent = '10';
  }
});


ngOnDestroy(): void {
  this._unsubscribeAll.next();
  this._unsubscribeAll.complete();
}

CodePudding user response:

As said on comments by R. Richards, you should always unsubscribe everything before destroying some instance.

You mentioned there was no way to unsubscribe an AbstractControl and really that is not possible. To unsubscribe you need to save the reference when you subscribe.

I would recommend you have an array of subscriptions that you iterate over when destroying the instance unsubscribing everything. Following your example, it would look like this:

subscriptions = [];

...

const typeCtrlSubscription = this.typeCtrl.valueChanges.subscribe((value) => {
    if (value === 'new') {
      this.percent = '20';
    } else {
      this.percent = '10';
    }
});

this.subscriptions.push(typeCtrlSubscription)

...

ngOnDestroy(): void {
    this.subscriptions.forEach((subscription) => subscription.unsubscribe())
}
  • Related