right way to use subscriptions in meteor

Cereal Killer

In my meteor app I have all pages that needs to load one or more documents from elements collection and a couple of pages that loads documents from items collection;

I have the two publish functions for the two collections, but now I'm trying to understand the best way to subscribe them; currently I'm subscribing elements in a file in the /client directory:

Meteor.subscribe("elements");

This will make the subscription on application start;

in the other case, since the items to be loaded are a little more, I've decided to use the subscription option in iron router:

subscriptions: function() {
    return Meteor.subscribe("items");
}

The first difference I can see is that it seems that elements, once started the application, will not take time anymore to load (navigating through pages takes no time for loading); on the other hand, every time I open the page that loads items, (event without a refresh) takes the loading time again;

Would be probably not the best solution to subscribe also items on application start, since they are only needed if you visit their specific route (elements otherwise are needed everywhere); but there is a way to avoid reloading them from the server every time I ask the route again?

Also thinking about elements, they are not needed all in all pages: avery page need just one or two of them; so it would be probably more corret to load just the one or two that are really needed...

How subscriptions should be managed in your opinion?

David Weldon

I cover some of the trade-offs in my answer to this question. Here's how we use do this at Edthena using the subscriptions manager package:

// Allow the subman to cache a lot of subscriptions for a very long time
var subman = new SubsManager({cacheLimit: 100, expireIn: 864000});

// This is a global subscription that we may need to wait on later
subman.subscribe('sub1');

// This is a global subscription that we don't need to wait on
Meteor.subscribe('sub2');

Tracker.autorun(function() {
  if (Meteor.userId()) {
    // Add subscriptions which should be loaded globally but only
    // after the user logs in.
    Meteor.subscribe('sub3');
  }
});

var PostController = RouteController.extend({
  waitOn: function() {
    // Use subman only if we want to cache the subscription between routes.
    // Note that in the case of sub1, the previous handle will be reused
    return [
      subman.subscribe('sub1'),
      subman.subscribe('sub4'),
      Meteor.subscribe('sub5')
    ];
  }
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related