Unsubscribe the client from subscription

I was wondering if there is an meteor “native” way to stop client’s subscriptions.

For example, i have 2 pages, on the first i subscribe the client to users publication, and on the second i subscribe to projects publication.

When the client goes from users page to the projects page, he is still subscribed to the users, although he does not need it on projects page.

So my first question is: Does it take memory or CPU? When the client is subscribing to more and more publications, when he goes from route to route.

And the second: What is the proper way to unsubscribe??
For example when he goes to projects page, unsubscribe from the users publication.

Some packages i see does that. For example reactive-table.

Thank you in advance!

Use template level subscriptions.

1 Like

Now when i subscribe from template level, the html is rendered before the subscription and so i dont have any data from DB rendered

I read about Template.subscriptionsReady(). But it seems like it is not reactive.Why??

Please help!

onCreated =
this.autorun(()=> { this.subscribe('allDocCategories'); });

helper =
docCategories: function(){ return DocCategories.find(); }

HTML (view) =
{{#if Template.subscriptionsReady}} {{#each docCategory in docCategories}} <option value="{{docCategory.title}}">{{docCategory.title}}</option> {{/each}} {{/if}}

Check out: https://www.discovermeteor.com/blog/template-level-subscriptions/

Seems ok after brief look. Are you sure there are no typos or other mistakes? Just debug - check if it’s subscriptionReady that is not working or find that is returning nothing.

This might not work. I am not 100% sure, but this could be wrong here. Try

Template.NAME.onCreated(function () {
  const template = this;
  template.autorun(() => {
     template.subscribe('allDocCategories');
  });
});

Template level subscriptions are automatically stopped when the template is destroyed.

However, your syntax is wrong and you do not need to put your subscription into an autorun because you are not using any reactive data in your parameter list (it won’t do any harm, it’s just not necessary here).

Template.thing.onCreated(function() { 
  this.subscribe('allDocCategories'); 
});

is all you need.

1 Like