abhilash reddy
abhilash reddy

Reputation: 1586

Receiving multiple instances of data from Behavior Subject every time component is initialised

I have a simple router where i am calling a service and receiving the data from the behavior Subject...When i navigate to another route and comeback i am receiving multiple values from the subject...How can i destroy all the observers of a subject and create new subject whenever i need...? Here is the plunker demo http://plnkr.co/edit/OKiljCekSKHO1zJF5MAy?p=preview
I am planning to destroy the observers of a subject in ngOnDestroy...

  ngOnDestroy(){
this.srvc.DestroySubject();
 }

Can somebody please tell me how to destroy the observers of a behaviorsubject?

Upvotes: 3

Views: 3691

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657406

The behavior is expected.

export class Sample1 {
  constructor(public srvc:HeroService) {
      this.srvc.Data.subscribe(data=> {
        console.log(data);
      });
      this.srvc.GetData();
  }
}

In the constructor you subscribe to srvc.Data and because Data is a BehaviorSubject it returns the most recent emitted value. You initialize Data with null, therefore at first there is no data.

Then in the constructor you call this.srvc.GetData() this causes an event to be emitted and be received by the subscription (the lines before).

If you navigate away and back, then Sample1 is initialized again and the constructor is executed. The first thing is that is subscribes to srvc.Data. and it gets the last emitted value which is Received Data from the previous call to GetData() (when we first navigated to Heroes).

The next thing is the call to this.srvc.GetData() which again emits Received Data and the subscription gets this value passed.

Workaround

To fix it you could move the call to this.srvc.GetData(); to the service instead like

@Injectable()
export class HeroService {
  Data: BehaviorSubject<RepairOrder> = new BehaviorSubject(null);

  constructor() {
    this.GetData();
  }

  GetData(){
    this.Data.next('Recieved Data');
  }
  DestroySubject(){
    //alert('hi');
  }
}

Plunker example

Upvotes: 3

Related Questions