Created
July 15, 2018 19:12
-
-
Save andrejewski/f5c8191b85436bd9227bc7d15d2a9063 to your computer and use it in GitHub Desktop.
A single value emitter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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