angularrxjsobservablesubscriptionbehaviorsubject

Complete BehaviorSubject


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


Solution

  • 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