Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
Should I be completing my subject after nexted in angular ngOnDestroy

I usually use takeUntil(this.destroySub) when I need to manually subscribe to a stream in my components. Does it matter (for the subject (garbage collection or whatnot) - since nexting is enough to complete the stream) whether I complete the subject or not in the ngOnDestroy?

@Component({...})
class MyComponent {
  private destroySub = new Subject<void>();

  constructor() { 
    of('some stream').pipe(
      takeUntil(this.destroySub)
    ).subscribe()
  }

  ngOnDestroy():void {
    this.destroySub.next();
    this.destroySub.complete();
  }
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Short Answer.

takeUntil(this.destroySub) is how you're completing all the other observables in your component, but this doesn't complete this.destroySub itself.

Yes, subjects don't have a finite lifetime, so you should complete them when you don't need them anymore.

The Longer Answer

Just like any other object, the GC will still collect a Subject once there are no more pointers to it. The issue with this way of thinking is that it's oh so very easy to accidentally leak a reference to this subject. Because it's an asynchronous library, references can be on both the current stack and the also the event loop.

Your working inside a framework that may try to optimize your components, so there's no guarantee the reference to your component is dropped inside Angular after ngOnDestroy is called. You're also passing references to the RxJS library for every time you use takeUntil(this.destroySub). RxJS proxies and manages emissions for you in many cases, so you may to surprised by a relatively mundane line of code causing a memory leak.

Completing an observable cleans up all the internal instrumentation that RxJS keeps for any given observable and leaves your conscious clear in that regard.

So yes, even though (if you're careful and well informed) the GC may clean up an incomplete observable, I wouldn't count on it. If your observable isn't finite, then make it finite somehow. this.destroySub.complete(); does that work for you.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!