0
votes

I have a BehaviourSubject defined in a service, and i point to that subject with a variable i define in another component, in that component's view i subscribe to the subject using that variable, example:

service:

public exampleSubjebt$ = new BehaviorSubject<boolean>(true);

component.ts:

ngOninit() {
let someVariable = this.service.exampleSubject$;
}

component's view:

<app-something [options]="someVariable | async"></app-something>

My question is, does the fact the the observable sits in the service and I call it directly from there using the variable, make it so that the async pipe will not unsubscribe on the component's destruction?

2
I assume someVariable is actually a property on the class?Kurt Hamilton
yeah that variable is a property in the class.Elazar Zadiki
async will always unsubscribe automatically. See also stackoverflow.com/questions/56033098/…martin

2 Answers

3
votes

The subscription lies into the component, not into the service so the async pipe will unsubscribe correctly when the component get destroyed.

0
votes

Yes it does unsubscribe. The async pipe is an angular directive, so it has all the lifecycles a component has. In the implementation i have found the following:

class ObservableStrategy implements SubscriptionStrategy {
  createSubscription(async: Observable<any>, updateLatestValue: any): SubscriptionLike {
    return async.subscribe({next: updateLatestValue, error: (e: any) => { throw e; }});
  }

  dispose(subscription: SubscriptionLike): void { subscription.unsubscribe(); }

  onDestroy(subscription: SubscriptionLike): void { subscription.unsubscribe(); }
}

In the ngOnDestroy they call the dispose

ngOnDestroy(): void {
  if (this._subscription) {
    this._dispose();
  }
}