Search code examples
angularrxjsbehaviorsubjectsubject

Should I complete BehaviorSubject on the component destroy – Angular2


I have a service provided in a component, so it runs ngOnDestory if the component is going to be destroyed. Every subscription runs with takeUntil(this.destory$) (which emits on the component's ngOnDestory hook) or with the async pipe, so everything is unsubscribed when the component destroys.

The question is, if I have a BehaviorSubject inside the service, should I run its .complete() and/or .unsubscribe() methods inside the service's ngOnDestory or I am good to go as it is?


Solution

  • Yes, you should unsubscribe on ngOnDestroy; not necessarily complete the subject if it is inside the service, because other components might still be using the subject and still need it to work properly.

    The services are singletons but their lifecycle depends on the injector in which they are provided. If your service is provided in the root injector, it lives as long as your application, so when you create the component that needs that subject again, you won't be able to reuse it without some sort of reinitialization.

    You mentioned that you do have takeUntil(this.destroy$) which should not lead to a memory leak, but be sure to also call complete on this.destroy$ inside your ngOnDestroy.

    ngOnDestroy() {
      this.destroy$.next();
      this.destroy$.complete();
    }