Search code examples
meteorpublish-subscribe

Meteor - why can't I store my Meteor.subscribe handle in the Session? I need to get it later to stop the subscription


I have the following code:

sub_geo = Meteor.subscribe('geo');
console.log('sub_geo returned from Meteor.subscribe: ');
console.log(sub_geo);
Session.set('sub_geo', sub_geo);
console.log('sub_geo retrieved from Session: ');
console.log(Session.get('sub_geo'));

The output is as follows:

sub_geo returned from Meteor.subscribe:
> Object {stop: function, ready: function}
sub_geo retrieved from Session:
> Object {}

Obviously I need to store the returned subscription handle because I need to call the ready() and stop() functions on it later. Not sure how else to store it other than in the Session. Can I just use a global variable? Also - even if there is some other way of doing it, why doesn't this approach work?


Solution

  • It doesn't work because you can only store EJSON-serializable objects in session variables. If you need the subscription handle outside of the current file, you'll need to store it in a global variable (perhaps under a namespace like Subscriptions - e.g. see richsilv's answer to this question.