Angular 2 - Is a subscription to FormControl valueChanges subscribed to unsubscribe?

Below is a simple example of what I'm asking:

class AppComponent {

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

  constructor(){

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

I have 2 questions:

1) Should I end up unsubscribing? 2) The most important thing, regardless of the answer to No. 1, WHY, what is the answer?

Any insight would be appreciated!

Thank!

+4
source share
2 answers
  • Yes Yes. Please note that you do not need to unsubscribe from http calls because they automatically terminate themselves.

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

, , , . , , valueChanges - 2 , , .

.

RxJS , takeUntil - , , :)

:

  private destroy$ = new Subject();

, , :

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

, :

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

, , , .

, , , ngFor, , valueChanges (, ). ngOnDestroy . takeUntil:)

( RxJS Google), takeUntil, /.

+5
  • .
  • , , , . .  . "auto unsubscribe after N time" - .take(numberOfTimes) N . :

    this.subscription = this.someInput.valueChanges
        .take(2) // unsubscribe after 2 times
        .subscribe(() => console.log("testing"));
    

    . , ngOnDestroy()

+2

Source: https://habr.com/ru/post/1665126/


All Articles