Skip to content

Instantly share code, notes, and snippets.

@cahnory
Last active November 29, 2017 11:48
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 cahnory/9e7238eae981799d2faecb9d6b64c999 to your computer and use it in GitHub Desktop.
Save cahnory/9e7238eae981799d2faecb9d6b64c999 to your computer and use it in GitHub Desktop.
Subscription manager to quickly remove all subs (on componentWillUnmount for eg.)
export default createSubscriptionManager = () => {
const subs = []
return {
subscriptions: subs,
interval: attachSubscriptionMethod(subs, interval),
listen: attachSubscriptionMethod(subs, listen),
timeout: attachSubscriptionMethod(subs, timeout),
promise: attachSubscriptionMethod(subs, promise),
remove: function() {
subs.forEach(sub => sub.remove())
subs.splice(0, subs.length)
return this
}
}
}
const attachSubscriptionMethod = (subs, callback) => (...args) => {
const sub = callback(...args)
subs.push(sub)
return sub
}
// Subscription methods
const timeout = (...args) => {
const ref = setTimeout(...args);
return {
remove: () => clearTimeout(ref)
}
}
const interval = (...args) => {
const ref = setInterval(...args);
return {
remove: () => clearInterval(ref)
}
}
const promise = promise => {
let removed, resolve, reject
promise.then(
res => !removed && resolve(res),
err => !removed && reject(err),
)
return Object.assign(new Promise((res, rej) => {
resolve = res
reject = rej
}),
{ remove: () => removed = true }
)
}
const listen = (listener, ...args) => listener.addEventListener(...args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment