How to explicitly unsubscribe?

I have MongoDB with a large collection of messages. All messages related to a specific groupId . So, we started by posting as follows:

 Meteor.publish("messages", function(groupId) { return Messages.find({ groupId: groupId }); }); 

and subscription:

 Deps.autorun(function() { return Meteor.subscribe("messages", Session.get("currentGroupId")); }); 

This caused me problems because initially the currentGroupId was undefined, but sill mongod would use the processor to search for messages using groupId == null (although I know they aren't).

Now I tried to rewrite the publication as follows:

 Meteor.publish("messages", function(groupId) { if (groupId) { return Messages.find({ groupId: groupId }); } else { return {}; // is this the way to return an empty publication!? } }); 

and / or rewrite a subscription to:

 Deps.autorun(function() { if (Session.get("currentGroupId")) { return Meteor.subscribe("messages", Session.get("currentGroupId")); } else { // can I put a Meteor.unsubscribe("messages") here!? } }); 

which initially helps. But as soon as currentGroupId becomes undefined again (as the user goes to another page), mongod is still busy reserving the database for the last signed groupId . So, how can I unsubscribe from a publication so that mongod stops being requested?

+8
meteor
source share
4 answers

Just adding a condition to the post:

 Meteor.publish("messages", function(groupId) { if (groupId) { return Messages.find({ groupId: groupId }); }); 

and save the subscription:

 Deps.autorun(function() { return Meteor.subscribe("messages", Session.get("currentGroupId")); }); 

performs the task.

There is no need to stop the publication explicitly. In the end, MongoDB is no longer queried after completing the current query and issuing another one (which seems to be queued somewhere on the system).

+5
source share

According to the documentation, this should be http://docs.meteor.com/#publish_stop

this.stop () Call the publish function. Stop this client subscription; the onError callback is not called on the client.

So something like

 Meteor.publish("messages", function(groupId) { if (groupId) { return Messages.find({ groupId: groupId }); } else { return this.stop(); } }); 

And I think on the client side you can just delete your if / else, as in the first example

 Deps.autorun(function() { return Meteor.subscribe("messages", Session.get("currentGroupId")); }); 
+7
source share

I found a simpler and more direct call to the .stop() function on a handler that returns from a .subscribe() call:

 let handler = Meteor.subscribe('items'); ... handler.stop(); 
+6
source share

in your case, you have to stop autorun

there is an example in the documentation

Your autostart is actually called with a parameter that allows you to stop it:

 Deps.autorun(function (c) { if (! Session.equals("shouldAlert", true)) return; c.stop(); alert("Oh no!"); }); 
0
source share

All Articles