-2

Hows best to unsubscribe from an observable using a takeUntil.

From what I understand takeUntil automatically does the complete for you.

Below is how I normally do a unsubscribe from an observable. But not sure if done correctly. Do I really need the "this.destroyed$.complete();" if takeUntil does the complete for me?

This is my current attempt that works but unsure if best method:

 private destroyed$: Subject<void> = new Subject();

 ngOnIt(): void {
    this.serviceA.getData
      .takeUntil(this.$destroyed)
      .subscribe(val => {
        console.log('Current value:', val);
      });
  };

  ngOnDestroy(): void {
    this.destroyed$.next();
    this.destroyed$.complete();
  };

I was thinking of removing the .complete in the ngOnDestory but not sure if that would cause memory leaks?

AngularM
  • 15,982
  • 28
  • 94
  • 169
  • 2
    have you check this link: https://stackoverflow.com/questions/38008334/angular-rxjs-when-should-i-unsubscribe-from-subscription ?* – Wandrille Oct 19 '17 at 20:13
  • That link has lots of examples and I just want an answer really for if I'm doing it right? Thanks for that link though – AngularM Oct 19 '17 at 20:22
  • 1
    Just read the validation answer: --- Edit 3 - The 'Official' Solution (2017/04/09). This is the best way, validated by team member from Angular – Wandrille Oct 19 '17 at 20:24
  • Wandrille, I've read the bit your referring too and it seems my solution above is correct. Do you agree? – AngularM Oct 19 '17 at 20:50
  • 1
    Yes, this is the good way. – Wandrille Oct 19 '17 at 21:24

1 Answers1

2

Personally I prefer this solution, have another subject just to handle unsubscribe and mix up with takeUntil probably make things too complex

 private _subscriptions:Subscription[];

 ngOnIt(): void {
  this._subscriptions.push(this.serviceA.getData
  .subscribe(val => {
    console.log('Current value:', val);
  })
   )
};

ngOnDestroy(): void {
this._subscriptions.foreach(subs=>{ subs.unsubscribe()})
};
Fan Cheung
  • 10,745
  • 3
  • 17
  • 39
  • I prefer my solution. But @Fan it would be good to know if yours definitely works because it's missing a complete() – AngularM Oct 20 '17 at 07:06
  • The objective is to unsubscribe everything upon NgDestroy, the oncomplete is the complete the side effect destroy subject in your approach so it's not quite related. – Fan Cheung Oct 20 '17 at 07:35