3

I’m using BehaviorSubject and subscribe to it using async pipe, do I need to complete the BehaviorSubject on component destroy? *I don’t subscribe to it on the .ts file

  • Async pipe will automatically unsubscribe, You can read more about here: https://angular.io/api/common/AsyncPipe#description – Chellappan வ May 11 '23 at 04:33

3 Answers3

4

complete() does 2 things:

  1. sends a completion signal to its subscribers, which triggers their completion callbacks
  2. unsubscribes all current subscribers and prevents new ones from subscribing

So if you only use the BehaviorSubject in your component, and only use it via async pipe, which manages its underlying subscriptions automatically (starts the subscription as soon as its template get executed, stops the subscription when the component is about to be destroyed), you don't have to call complete().

If however this BehaviorSubject exists in a shared service and/or is used by multiple subscribers, calling complete() might either be a mistake, because you would complete it for all subscribers, not just your component. Or, depending on your needs, it might be actually needed if you indeed want to clean up the BehaviorSubject completely.


To sum it up, I think it makes sense to

  • call complete() where the Subject is shared, or you care about the completion event, and
  • not to call it where the Subject is "private" to your class, you don't care about the completion event and you make sure you unsubscribe all your subscriptions, which sounds like a lot of conditions but is usually the case for most components
Dan Macak
  • 16,109
  • 3
  • 26
  • 43
0

If you are accessing behavior subject with async pipe in that case you do not need to manually unsubscribe that subject into your .ts file, angular will automatically unsubscribe for you when specific component is destroyed.

However, if you are manually subscribing subject into your component .ts file only in that case you should have to manually unsubscribe from your component ngOnDestroy() life cycle hook to avoid memory leaks errors.

Hope you get your answer, Thanks!

Jay Patel
  • 251
  • 3
  • 9
0

you could use complete() in ngOnDestroy()

ngOnDestroy() {
 this.subject.complete();
}