According to observe docs, I must define and call a stop function, or my observer will run forever. The point, is how to call stop if the user decided to close his browser before the expected time, for example? How can I call stop if a conection is dead?
2 Answers
To do this, you can call it inside your publish:
this.session.socket.on("close", function() { /*do your thing*/});
So, if you wanna stop an observer...
Meteor.publish("something", function () {
// ...
// your observers code here
// ...
self.onStop(function () {
handle.stop();
});
this.session.socket.on("close", function() {
handle.stop();
});
});
Answer found here. Thanks goes to Zhou Huabing.
You don't actually need to worry about disconnects. Any time the subscription stops (whether the client disconnects, or calls unsub, or you call this.stop
), the server will run all the registered onStop
handlers before tearing down the active subscription. (Teardown doesn't happen immediately on disconnect, by the way, but it will eventually. The idea is to wait a bit, in case the client tries to reconnect and resume its session.)
What you do need to do is make sure to register an onStop
handler that cleans up any resources your code used. Again, that needs to happen anytime the subscription is stopped. onStop
is the right hook. It's critically important to call stop
on an active observe, for example, just like in the first code stanza in the example.

- 11,870
- 2
- 49
- 43