Skip to content

Instantly share code, notes, and snippets.

@andrejewski
Created July 15, 2018 19:12
Show Gist options
  • Save andrejewski/f5c8191b85436bd9227bc7d15d2a9063 to your computer and use it in GitHub Desktop.
Save andrejewski/f5c8191b85436bd9227bc7d15d2a9063 to your computer and use it in GitHub Desktop.
A single value emitter
exports.createEmitter = function createEmitter ({ shouldPrime, initialValue }) {
let currentValue = initialValue
let listeners = []
return {
emit: value => () => {
currentValue = value
listeners.forEach(listener => listener(currentValue))
},
subscribe () {
let listener
return {
effect (dispatch) {
listener = dispatch
listeners.push(listener)
if (shouldPrime) {
listener(currentValue)
}
},
cancel () {
listeners = listeners.filter(l => l !== listener)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment