-1
  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?

R. Richards
  • 24,603
  • 10
  • 64
  • 64
  • unsubscribe, always – R. Richards Oct 25 '22 at 23:36
  • how? it dont have option of unsubscribe when is AbstracControl tell me: Property 'unsubscribte' does not exist on type 'AbstractControl'.ts(2339) @R.Richards – Jorge Angel Oct 25 '22 at 23:45
  • You only need to unsubscribe from infinite observables. So in this case, yes you need to unsubscribe. You don't need to unsubscribe from observables that complete, like http requests. This is described extensively here: https://stackoverflow.com/a/41177163/12914833 The return value of `subscribe()` is the function that unsubscribes. – Chris Hamilton Oct 26 '22 at 00:42

2 Answers2

1

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();
}
  • You should check the docu, if you need to unsubscribe. Not every subscription stays open, e.g. material dialog afterClosed subscription completes itself. – hmartini Oct 26 '22 at 22:17
0

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());
}