Created
May 2, 2019 13:49
-
-
Save Noitidart/e4887dc70271f8f466004eae3cdb3e6d to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* A caveat is that an observer, referentially, can ONLY subscribe to one type. | |
* I can fix this in the future, but for now, I don't have a need. | |
* | |
* @param {"connect" | "reconnect" | "disconnect"} type | |
* @param {Function} observer | |
* @param {Object<string, any>} options | |
* @param {boolean} [options.shouldMulti] - Set to true if you want the observer to stay subscribed after first trigger. By default, it will be removed after first trigger. | |
* | |
* @returns {Function} unsubscribe | |
*/ | |
function subscribeToSocket(type, observer, options = { | |
shouldMulti: false | |
}) { | |
if (gObservers.has(observer)) { | |
throw new Error('This observer was previously added.'); | |
} | |
gObservers.set(observer, options); | |
return () => unsubscribeFromSocket(observer); | |
} | |
function unsubscribeFromSocket(observer) { | |
gObservers.delete(observer); | |
} | |
function _triggerObservers(type) { | |
for (const [observer, options] of gObservers) { | |
observer(); | |
if (!options.shouldMulti) { | |
gObservers.delete(observer); | |
} | |
} | |
} | |
function _triggerConnectObservers() { | |
_triggerObservers('connect'); | |
} | |
function _triggerDisconnectObservers() { | |
_triggerObservers('disconnect'); | |
} | |
function _triggerReconnectObservers() { | |
_triggerObservers('reconnect'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment