Skip to content

Instantly share code, notes, and snippets.

@colbydauph
Created February 7, 2018 07:06
Show Gist options
  • Save colbydauph/24590bbff632927ab8202842b3282ac8 to your computer and use it in GitHub Desktop.
Save colbydauph/24590bbff632927ab8202842b3282ac8 to your computer and use it in GitHub Desktop.
Subscribe to Online / Offline Changes
// subscribe to online / offline events
// (bool -> undefined) -> () -> undefined
const subscribeOnline = (cb) => {
const online = () => cb(true);
const offline = () => cb(false);
window.addEventListener('online', online, false);
window.addEventListener('offline', offline, false);
return function unsubscribe() {
window.removeEventListener('online', online);
window.removeEventListener('offline', offline);
};
};
/* usage */
// subscribe
const unsub = subscribeOnline((online) => {
console.log(`Online? ${ online }`);
});
// unsubscribe
unsub();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment