Meteor subscriptions not stopping


#1

I’ve got what should be a relatively simple issue. I set a session, then a subscribe to a collection using the string stored in the session. But when that session changes, I need to clear the subscription data and start again.

My code is as follows:

let subscriptionReady;
let filteredResults = [];
let rawResults = [];
let county = Session.get('county');
let type = Session.get('type');

This is mostly just prep work to create some empty objects to populate later. This all gets set on a click event. After we set these placeholder objects we go and subscribe by those sessions:

  if (county && !type) {
    return function() {
      if (subscriptionReady) {
        subscriptionReady.stop();
      }

      filteredResults = [];
      rawResults = [];

      subscriptionReady = Meteor.subscribe('resourcesearch', county, {
        onReady: () => {
          rawResults = resourceCollection.find({}, { sort: {score: -1} }).fetch();

          rawResults.forEach((result) => {
            if (result.score) {
              filteredResults.push(result);
            }
          });
        }
      });
    }

At the third line I run a check to see if subscriptionReady exists, then it will have the stop method available. So then I run it. But, it doesn’t actually stop anything and so if the county Session changes and we re-run this, we’ll get county[0] data as well as county[1] data.

What am I missing?


#2

#3

After trial and error, I’ve got it solved. The issue was the placement of the stop call. I no longer have to check if subscriptionReady exists, instead I stop the subscription inside of the onReady method:

    return function() {
      filteredResults = [];
      rawResults = [];

      subscriptionReady = Meteor.subscribe('resourcesearch', county, {
        onReady: () => {
          rawResults = resourceCollection.find({}, { sort: {score: -1} }).fetch();

          rawResults.forEach((result) => {
            if (result.score) {
              filteredResults.push(result);
            }
          });            

          subscriptionReady.stop();
        }
      });