Is BehaviourSubject needed with Ionic3 Lazy Loading?

My understanding is that BahviourSubject is better than using @Output+EventEmiter, since it is more memory efficient.
You subscribe when the page is loaded, and unsubscribe before page exits (ionViewWillUnload).
However, if Ionic3 Lazy Loading is destroying the page/component that contains the Event Emitter/Event Listener, and removing it from memory (My undersating of Lazy Loading), what difference does it make if I have an event Listener or a subscribed observer?
I am trying to figure out how to test the difference with profile recording in Chrome Devtools…

BehaviorSubjects make the most sense in global providers. If you’re just working inside a page, the communication can be synchronous. But if a global AuthProvider needs to broadcast that the user has logged in or logged out, the auth value can be the next of a BehaviorSubject, and the pages that need that information can subscribe to the BehaviorSubject.asObservable().

Edit: If you mean between page and component, BehaviorSubject is especially useful as the Input() to a component, so the component refreshes every time the page changes the input value.

1 Like

Thanks for the answer Aaron. I agree that BehaviourSubject makes sense from a convenience point of view. My question still stands regarding the memory efficiency.

The answer could change tomorrow when libraries change, and change again the day after that. Unless you’re programming a microcontroller, that isn’t really a question to ask in the 21st century. This is hybrid programming, inside half a dozen different browsers across at least 4 different platforms. What matters is memory leaks, not memory. As long as a construction has a stable footprint, it doesn’t matter how large that footprint is. You can’t control it anyway.

1 Like

Hello Aaron,

did you have a short code example how you use that BehaviourSubject as input in component?

Thanks in advance, anna-liebt

@Input() 
    set nameOfInput(value) {
      this.currentInput.next(value); // currentInput is a BehaviorSubject
    }
    get nameOfInput() {
      return this.currentInput.getValue();
    }
ngOnInit() {
  this.currentInput.asObservable().subscribe( x => console.log(x));  // x is what you use in your HTML
}

Hello Aaron,

thank you a lot.

Best regards, anna-liebt.

Chek out the 2nd answer on this SO - https://stackoverflow.com/questions/34088209/how-to-pass-object-from-one-component-to-another-in-angular-2

We have been minimizing our use of BehaviorSubject in components and pages. If you pass input and navParams as objects and then change the source, the compoennt/page will get updated, since it is passed by reference and not by value. So we never really need @Output which is really nice.