Yanick Rochon Yanick Rochon - 1 year ago 148
Javascript Question

Understanding Meteor subscription

I don't understand this example from react-meteor-data

import { createContainer } from 'meteor/react-meteor-data';

export default FooContainer = createContainer(() => {
// Do all your reactive data access in this method.
// Note that this subscription will get cleaned up when your component is unmounted
var handle = Meteor.subscribe("todoList", this.props.id);

return {
currentUser: Meteor.user(),
listLoading: ! handle.ready(),
tasks: Tasks.find({listId: this.props.id}).fetch(),
}, Foo);

Why is it recommended to
subscriptions when a
is umounted but, in this case, no effort is made to stop anything? How does Meteor handle subscriptions, then? When are the collections cleaned? Are subscriptions stacking up every time the tracker callback is executed?

Or is Meteor smart enough to know when
is being called and does magic with the subscriptions?

Answer Source

The ReactMeteorData container runs createContainer's callback inside a reactive Tracker computation.

One of its features is stopping the subscription if the computation is invalidated or stopped.

If the function re-run produces an identical subscription, (same publication, same parameters) the library is smart enough and does not cancel and re-create the same subscription.

When the component is unmounted, the computation is stopped, the subscription is cancelled and not re-created (as the callback is not called again) and therefore automatically unsubscribed.

If you call Meteor.subscribe within a reactive computation, for example using Tracker.autorun, the subscription will automatically be cancelled when the computation is invalidated or stopped; it is not necessary to call stop on subscriptions made from inside autorun. However, if the next iteration of your run function subscribes to the same record set (same name and parameters), Meteor is smart enough to skip a wasteful unsubscribe/resubscribe.

(source: Meteor Docs)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download