Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.