1

I'm reading an article about the rxjs concatMap operator. This guy builds an autosave form, i.e., whenever the user types a letter the data is saved using a http request

this.subscription = this.form.valueChanges
      .pipe(concatMap(formValue => this.http.put(`/api/course/${courseId}`, formValue)))
      .subscribe(saveResult =>  ... handle successful save ...);

I want to be able to unsubscribe in ngOnDestroy() from the valueChanges Observable, but the this.subscription Subscription refers to the http observable. So how can I unsubscribe from valueChanges?

Mateut Alin
  • 1,173
  • 4
  • 17
  • 34
  • 1
    If you call `this.subscription.unsubscribe()` any inner Observable inside `concatMap` is unsubscribed as well because this will dispose the whole chain. – martin Mar 01 '19 at 14:34
  • So `valueChanges` will be unsubscribed, right? Can you give me a reference? – Mateut Alin Mar 01 '19 at 14:35
  • 1
    That's how RxJS works. See https://rxjs.dev/guide/subscription, https://stackoverflow.com/questions/38008334/angular-rxjs-when-should-i-unsubscribe-from-subscription and https://stackoverflow.com/questions/38008334/angular-rxjs-when-should-i-unsubscribe-from-subscription/41177163#41177163 – martin Mar 01 '19 at 14:40

1 Answers1

1

In your ngOnDestroy function simply use your reference to the subscription. When you create the observable it returns back a subscription object which exposes the unsubscribe() method.

ngOnDestroy{
this.subscription.unsubscribe();
}
sreisman
  • 658
  • 3
  • 9
  • 24