Search code examples
angularbehaviorsubject

BehaviorSubject is executed more than once


I am using angular 4 for my app and I use behaviorSubject to communicate between component, everythings were working fine

Here is my code:

export class Globals {
loadStudentsByClass: BehaviorSubject<string> = new BehaviorSubject<string>(null);
}

export class ClassComponent implements OnInit {
selectNewClass() {
    console.log('About to select new class', this.selectedClass);
    this.globals.loadStudentsByClass.next(this.selectedClass); 
    this.globals.changeClassBehavior.next(true);
    this.router.navigateByUrl('');
  }
}

export class StudentComponent implements OnInit {
    this.globals.loadStudentsByClass.subscribe(value => {
          if (!isNullOrUndefined(value) && this.selectedClass !== value) {
            console.log('loadStudentsByClass=> home');
            this.loadStudentsByClass(this.selectedClass);
          }
        });
}

So, I have the component ClassComponent who triggers the StudentComponent to call the function loadStudentsByClass.

This is the only place where I call this behavior subject, but I find my behavior Subject emitted more than once

The problem is why behaviorSubject execute loadStudentsByClass more than once although this.globals.loadStudentsByClass.next(this.selectedClass); is called only one time

By the way the number of execution depends on the numbers of views I visited in the application


Solution

  • You probably forgot to unsubscribe in your StudentComponent when the components gets destroyed. Save the subscription in a class variable and in ngOnDestroy() lifecycle hook call subscription.unsubscribe()