tadasajon
tadasajon

Reputation: 14856

Meteor - how can I empty out the collection of 10,000 objects I subscribed to after I no longer need it?

I have a template in which a user should be able to click on a button to bring up a modal and in the modal choose a handful of items out of a list of about 10,000 items which are displayed there to search or scroll through.

Since this collection is so big, I don't want to keep it around in memory when I don't absolutely need it.

So I would like to subscribe to this collection only when the modal is being viewed and I would like to ensure that I am unsubscribed if the modal is not being viewed.

Is there a way to explicitly unsubscribe from a collection?

Upvotes: 1

Views: 99

Answers (2)

David Weldon
David Weldon

Reputation: 64312

There are a couple of ways you can do this:

  1. Use the subscription handle

subscribe returns a handle you can call stop on. For example:

var handle = Meteor.subscribe('stuff');
handle.stop();
  1. Use an autorun

Because an autorun will automatically start and stop subscriptions when its reactive dependencies change, this will work:

Tracker.autorun(function () {
  if (Session.get('showingModal'))
    Meteor.subscribe('stuff');
});

Side note - it may make more sense to use a method call for searching such a large data set rather than publishing the entire thing to the client. For example you can set a session variable whenever the user's query changes, then use an autorun to update the result set based on the method's return value.

Upvotes: 3

saimeunt
saimeunt

Reputation: 22696

https://docs.meteor.com/#/full/meteor_subscribe

Quoting the docs :

Meteor.subscribe returns a subscription handle, which is an object with the following methods:

stop() Cancel the subscription. This will typically result in the server directing the client to remove the subscription's data from the client's cache.

So basically what you need to do is storing the subscription handle in a variable and call the stop method when you don't need those published documents anymore.

Note that if you're using iron:router (and you probably should), this is taken care of automatically for you on each route change, which is convenient but has the side effect of provoking a lot of sometimes unnecessary calls to Meteor.publish calls which are non trivial for the server and bandwidth... to address this matter you can use meteorhacks:subs-manager but it's another topic anyway.

Upvotes: 1

Related Questions