Angular-meteor $reactive and ionic view caching

What is the best practice for handing angular-meteor reactivity and ionic ion-view caching? Especially when using controllerAs

when do you call $reactive(this).stop()? How do you handle subscribe()'?

for example:

var myModule = angular.module('myApp', ['angular-meteor']);

myModule.controller('MyCtrl', ['$scope', '$reactive', function($scope, $reactive) {
  $reactive(this).attach($scope);

  this.age = 10;

  this.subscribe('users', () => [
    this.age
  ]);

  this.helpers({
    users: () => Users.find({});
  });

  // when do you call $reactive(this).stop()?
  $scope.$on('$ionicView.leave', (e)=>
      $reactive(this).stop();

  $scope.$on('$ionicView.unloaded',  (e)=>
      $reactive(this).stop();

  $scope.$on('$ionicView.enter', (e)=>
      // do you have to subscribe again if you called stop()?
      this.subscribe('users', () => [
        this.age
      ]);

}]);

Dear @mixersoft. This is a complex issue and for now there is no clean solution for it. I will start with few notes after observing your code:

  • You don’t have to call $reactive() again If you already did, all it does is extending the $scope and the view model (In this case, the controller).
  • A $reactive() call should always be followed by attach() otherwise the Meteor methods will not be bound to the $scope.
  • It is recommended to call $scope.viewModel(this) rather than $reactive(this).attach($scope) based on angular-meteor's internal mixins architecture.
  • $reactive(this).attach($scope).stop() doesn’t exist.

What actually happens behind the scenes is that any time you call a Meteor function like subscribe() and autorun() a stop() event will be registered and triggered once the $destroy event is broadcasted. The only way to stop them would be by calling $scope.$broadcast('$destroy) which is not recommended since other third party libraries might also be dependent on them. In addition, when you invoke the helpers() method, it will be registering computations behind the scenes whose access is unreachable.

With that said, a single subscription can easily be stopped by calling the Subscribe.stop() method. So I would use the following code snippet:

const myModule = angular.module('myApp', ['angular-meteor']);

myModule.controller('MyCtrl', ['$scope', '$reactive', function($scope, $reactive) {
  $reactive(this).attach($scope);

  this.age = 10;

  this.subscribeToUsers = () => {
    this.usersSub = this.subscribe('users', () => [
      this.age
    ]);
  };

  this.subscribeToUsers();
  this.helpers({
    users: () => Users.find({});
  });

  $scope.$on('$ionicView.leave', e =>
    this.usersSub.stop();
  );

  $scope.$on('$ionicView.unloaded', e =>
    this.usersSub.stop();
  );

  $scope.$on('$ionicView.enter', e =>
    this.subscribeToUsers()
  );
}]);

If you have an issue or a feature request you can go to angular-meteor’s issues page and submit a new topic.