0
votes

I have a service with a behaviorSubject element, like this:

 public _changeAlert = new BehaviorSubject<myMsg>(null);
 public changeAlert = this._changeAlert.asObservable();
 public sendAlert(msg$: string){
     this._changeAlert.next(msg$);
   }

And have a subscriber receiverComponent.ts

 alerterPointer: any;
 constructor(private alertSrv: alertService){
     this.alerterPointer = this.alertSrv.changeAlert.subscribe(msg$ => {console.info(msg$)});

   }
}
ngOnDestroy(){
     this.alerterPointer.unsubscribe();

component that sends/broadcast alert alerter.ts

  sendAlert(){
    this.alertSrv.sendAlert('Hello world');
}

My issue is that, even after unsubscribing, if I naviate to another component and come back to the receiverComponent.ts, it actually gets the "hello world" instead of the null value of the initial subscription. In other words, it remembers the last alert broadcasted.

How do I avoid this leak ? ... I'm using this approach all over my project and have substantial leaks bc of this behavior.

(pls don't tag it as duplicated, I checked the similar question but it doesn't address the same issue)

thanks !

3
So what do you expect it to be 'null'? where is BehaviorSubject defined? some service outside of components? this seems like works as it was intended case. - Sergey Rudenko
Are you listing that service as a provider in the module that declares those components? Could you post the code for that module and the service with the decorator and its metadata. - nullptr.t
Thank you all. The way I see it, bs are like broadcasters on angularJS and I thought there would be a more graceful way (garbage collector style) to dispose of these subscriptions. I was already calling the service with the null value on destroy, this way the last call to receive was that of a null value, in which case I have logic in place to ignore it, but again, always thought there was a more elegant way of doing this. - Mike Gmez

3 Answers

4
votes

If you want current value then you can use Subject instead of behaviorSubject

0
votes

What is happening here is that your BehaviourSubject exist in your service. As a very simple workaround you could emit a new value on your onDestroy to force the BehaviourSubject to have a null value.

 this._changeAlert.next(null);

That way the next time you'll get null instead of Hello World

0
votes

You are describing the way BehaviorSubject works. BehaviorSubject stores the latest value emitted. Whenever a new Observer subscribes, it will immediately receive the "current value" from the BehaviorSubject. If you do not need this switch to Subject as already @UmeshB, @[Jose Guzman] and @[Ashot Aleqsanyan] suggested you.