Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

rxjs - Angular 2 - Does subscribing to FormControl's valueChanges need an unsubscribe?

Below is a simple example of what I am asking about:

class AppComponent {

  someInput: FormControl = new FormControl('');
  private subscription: Subscription;

  constructor(){

    this.subscription = this.someInput.valueChanges
        .subscribe(() => console.log("testing"));
  }
}

I have 2 questions:

1) Do I have to eventually unsubscribe from this? 2) Most importantly, whatever the answer is to #1, WHY is that the answer?

Any insight would be appreciated!

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

UPDATE OCT 2020

This question gets a lot of SEO traffic and whilst my answer is still technically correct, I strongly advise you to read this.


  1. Yes, you do. Note that you do not need to unsubscribe from http calls because they auto-complete themselves.

  2. You must unsubscribe to prevent memory leaks and to avoid unexpected side-effects in your application.

For example, when a component is destroyed, the subscription will remain if you don't unsubscribe from it. The next time the user navigates back to that page and the component gets loaded again, it will create another subscription to valueChanges - now you have 2 active subscriptions processing data simultaneously and that will lead to unexpected behavior in your app.

There is a relatively easy way to setup auto-unsubscribing.

The RxJS way is to use takeUntil - it basically lets you set up a subscriber which keeps listening UNTIL you tell it not to :)

First we need a destroy subject in our component:

  private destroy$ = new Subject();

Then tell it to emit a value when our component is destroyed:

  ngOnDestroy(){
    this.destroy$.next();
    this.destroy$.complete(); 
  }

Now setup your subscribes to use it:

this.someInput.valueChanges
  .debounceTime(1000)
  .distinctUntilChanged()
  .takeUntil(this.destroy$)
  .subscribe (newValue => {

All the subscribes setup like this will then auto-unsubscribe when they receive the destroy notification.

This is especially useful if, for example, you have an ngFor that is dynamically adding controls, and each control added has an valueChanges subscription (eg. an array of controls). In such a scenario you don't need to loop through the array in ngOnDestroy and unsubscribe one-by-one. Just use takeUntil :)

I recommend reading Ben Lesh's article (RxJS lead engineer at Google) for a great overview of takeUntil, including pros/cons.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...