Skip to content

Instantly share code, notes, and snippets.

@rdb
Last active April 19, 2020 21:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rdb/e0d04b8bee673371b4e3741ac1426c03 to your computer and use it in GitHub Desktop.
Save rdb/e0d04b8bee673371b4e3741ac1426c03 to your computer and use it in GitHub Desktop.
Patches Meteor.subscribe and Tracker.autorun to stop when a Svelte component is destroyed. Also supports await block for subscriptions.
import { current_component } from 'svelte/internal';
_autorun = Tracker.autorun;
Tracker.autorun = function autorun() {
const computation = _autorun.apply(this, arguments);
if (current_component) {
current_component.$$.on_destroy.push(computation.stop.bind(computation));
}
return computation;
};
_subscribe = Meteor.subscribe;
Meteor.subscribe = function subscribe(name) {
const params = Array.from(arguments);
let callbacks = Object.create(null);
if (params.length > 1) {
// Preserve existing callbacks.
// Last arg may be specified as a function, or as an object
const last = params[params.length - 1];
if (typeof last === 'function') {
callbacks.onReady = params.pop();
} else if (last && [last.onReady, last.onError, last.onStop].some(f => typeof f === "function")) {
callbacks = params.pop();
}
}
params.push(callbacks);
let subscription;
// Collect callbacks to call when subscription is ready or has errored.
let readyCallbacks = [];
let errorCallbacks = [];
if (callbacks.onReady) {
readyCallbacks.push(callbacks.onReady);
}
if (callbacks.onError) {
errorCallbacks.push(callbacks.onError);
}
callbacks.onReady = () => {
readyCallbacks.forEach(fn => fn(subscription));
readyCallbacks.length = 0;
};
callbacks.onError = (err) => {
errorCallbacks.forEach(fn => fn(err));
errorCallbacks.length = 0;
};
subscription = _subscribe.apply(this, params);
if (current_component) {
current_component.$$.on_destroy.push(subscription.stop.bind(subscription));
}
subscription.then = (fn, err) => {
readyCallbacks.push(fn);
err && errorCallbacks.push(err);
};
return subscription;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment