3

I am trying to understand subscriptions in angular and after some reading I have taken the below approach.

I am using .pipe(takeUntil()) in order to unsubscribe.

Is this the right way to check if the subscription has successfully unsubscribed

// subject I'm using to unsubscribe subscriptions
private onDestroy$ = new Subject();

// The call to load data
this.service.method()
  .pipe(
    takeUntil(this.onDestroy$),
    tap(() => console.log('unsubscribed')) // <== does this run when it unsubscribes ?
  )
  .subscribe((pData => {
  });

OnDestroy:

ngOnDestroy() {
   this.onDestroy$.next(); <== is this necessary ? I'm not sending data
   this.onDestroy$.complete();
}

I have aslo read that you do not need to unsubscribe from HTTP requests as it runs the complete() after getting the result and unsubscribes itself, is that correct?

Can you please explain this next statement to me aswell:

"Using an operator like takeUntil instead of manually unsubscribing will also complete the observable, triggering any completion event on the observable."

Jayme
  • 1,776
  • 10
  • 28
  • 1
    Here is some explanation about a similar question : https://stackoverflow.com/questions/54092776/angular-7-am-i-creating-too-many-subscriptions/54093438#54093438 – Florian Jan 16 '19 at 09:45
  • Make sure that `takeUntil` is always the last operation you use in `pipe()`, it creates a mirror of your observable source, and you subscribe on this mirror. When you destroy the component, you complete the mirror, so all subscriptions on this mirror are destroyed. – Florian Jan 16 '19 at 09:47
  • Does it have to be last even if the next operator does not use a observable, in this case, it just writes a log ? – Jayme Jan 16 '19 at 09:48
  • https://blog.angularindepth.com/rxjs-avoiding-takeuntil-leaks-fb5182d047ef – Jayme Jan 16 '19 at 09:49
  • Yes, this link will explain better than I can ! :) – Florian Jan 16 '19 at 09:51

0 Answers0