2

I am trying to troubleshoot my code. I expect the subscription to trigger on .next() and on initilization.

But it triggers once the first time, then i navigate away and come back to the component and trigger the next and it fires twice. and i navigate away and return and it fires trice.

I have check all the function that call .next() and they are only triggered once but the subscription is still getting incremented.

My behaviorsubject is inside a service and when i click on a component it calls the next function inside the service.

any thoughts on where else i can check for the issue or how

Narm
  • 10,677
  • 5
  • 41
  • 54
JSB
  • 221
  • 2
  • 13

2 Answers2

2

From you description it sounds like you're not unsubscribing from your BehaviorSubject in your component. If you don't unsubscribe then every time you initialize that component (navigate to it) you create a new subscription to the behavior subject. Since you don't unsubscribe from that BehaviorSubject when you navigate away that subscription is left active. Hence when you return a second time, yet another subscription is created and then you begin receiving multiple next() notifications. This behavior is known as a memory leak.

In your component that you subscribe to your behavior subject you will want to do something like this:

export class AppComponent implements OnInit, OnDestroy {
  private mySub;

  constructor(private yourService: YourService){}

  ngOnInit(){
    this.mySub = this.yourService.yourBehaviorSubject.subscribe({
      next: _ => //Do stuff
    });
  }

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

}

This is of course is all speculation as to what your underlying issue is, because you did not provide any code! If my suspicion is wrong then please provide some code. That would help greatly! :)

Narm
  • 10,677
  • 5
  • 41
  • 54
  • Thanks for the input. I also thought of this. it is hard for me to create a small sample of the code. But i added an unsub function but afterward i would get the observable unsub error. so i am confused. I might end up refactoring the whole thing anyway – JSB Feb 16 '19 at 03:39
2

Either you need to unsubscribe the subscription on leaving the component as

  ngOnInit(){
    this.subscriptionObj1 = this.service.behaviorSubject1.subscribe({

    });

    this.subscriptionObj2 = this.service.behaviorSubject2.subscribe({

    });
  }

  ngOnDestroy(){
    this.subscriptionObj1.unsubscribe();
    this.subscriptionObj2.unsubscribe();
  }

Or if you are lazy to check for all the occurrences of subject subscription in all the code. :)

Just add pipe(first()) It will auto unsubscribe the object after 1st execution.

import { first, take } from 'rxjs/operators';

 ngOnInit(){
        this.service.behaviorSubject1.pipe(first()).subscribe({

        });
        this.service.behaviorSubject2.pipe(first()).subscribe({

        });
  }
AlpeshVasani
  • 227
  • 4
  • 15