javascript - Should I unsubscribe from Angular Form changes? - Stack Overflow

When subscribing to changes in an Angular Abstract Control using valueChanges, is it necessary to unsub

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.

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.

Share Improve this question edited Jun 26, 2018 at 15:10 Jack asked Jun 26, 2018 at 14:46 JackJack 10.6k16 gold badges78 silver badges129 bronze badges 1
  • 1 Very good question, I was thinking the same, 1+ upvote from me :) – user6600549 Commented Mar 15, 2019 at 11:08
Add a ment  | 

1 Answer 1

Reset to default 7

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

https://medium./@benlesh/rxjs-dont-unsubscribe-6753ed4fda87

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742398850a4436498.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信