Search code examples
angularrxjsbehaviorsubject

Rxjs, Angular subscription getting "ObjectUnsubscribedError"


I have a service that defines a bunch of BehaviorSubject objects that are subscribed to by the top level component, and the data is coming from the back end, but that just populates the subjects with data that the component subscribes to. I'm also using ngOnDestroy to .unsubscribe() everything that's been subscribed to.

The issue comes in when I'm adding a new component below the level of the top level component that also gets injected with the service, also subscribes to data on the service, and also unsubscribes inside ngOnDestroy. This looks fine in code, but in practice it's causing some errors.

Sometimes when the component is constructed, I get some ObjectUnsubscribedError's in there, and from what I can tell the BehaviorSubject's that I'm subscribing to have a closed:true property that appears to be the source of the errors.


Solution

  • Without seeing some code it's tough to know for sure, but it sounds like you are calling .unsubscribe() on the BehaviorSubject directly instead of the Subscription. Consider the following:

    const source = new BehaviorSubject('some-value');
    source.subscribe();
    source.unsubscribe();
    source.subscribe(); // <-- This line will throw ObjectUnsubscribedError
    

    Instead of the above, do the following:

    const source = new BehaviorSubject('some-value');
    const subscription = source.subscribe();
    // And when it's time to unsubscribe in ngOnDestroy...
    subscription.unsubscribe();