Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop and restart collection observers in Meteor?

I want to be able to stop and restart observers on my collections in Meteor.

Imagine I have the following observer:

 // Imagine some collection of Blog posts "Posts"
  Posts.find().observe({
    changed: notifySubscribedUsers
  });

 // function notifySubscribedUsers() { ... }  
 //    is some function that will email everyone saying some post was updated

Now imagine I want to update lots of Posts, but I dont want the observers to be called. How can I get access to the observers, stop/pause them and then later restart them (after the db job is finished) ?

TIA

like image 908
Mike Graf Avatar asked Jan 15 '14 21:01

Mike Graf


1 Answers

The observer returns a handle:

var handle = Posts.find().observe({
    changed: notifySubscribedUsers
});

Then you can stop it with:

handle.stop()

It's not possible to 'pause' it in the conventional sense, if you want to pause it you could just ignore the data it gives you.

To do this in a neat wrapped up method you could do something like:

var handle;

var start = function() {
   if(handle) handle.stop();
   var handle = Posts.find().observe({
    changed: notifySubscribedUsers
   });
}

var stop = function() { if(handle) handle.stop }

Or to put it on a collection:

// posts.js collection file
Posts.startObservers = function startObservers() {
  Posts.observer = Posts.find().observe({
    change: notifySubscribedUsers // or some other function
  });
};

Posts.stopObservers = function stopObservers() {
  if(Posts.observer) {
    Posts.observer.stop(); // Call the stop
  }
};


// Trigger Somewhere else in the code
Posts.stopObservers();
MyTool.doWorkOnPosts(); // Some contrived work on the Posts collection
Posts.startObservers();
like image 122
Tarang Avatar answered Nov 16 '22 05:11

Tarang