Skip to content

Instantly share code, notes, and snippets.

@kudarap
Created February 12, 2017 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kudarap/45c14f9b0a51e0db4092451d6ef6cadd to your computer and use it in GitHub Desktop.
Save kudarap/45c14f9b0a51e0db4092451d6ef6cadd to your computer and use it in GitHub Desktop.
SSE auto-revive connection
export const ImmortalSSE = url => {
let url
let instance
let listeners = []
const timeout = 2000
const create = () => {
if (url == undefined) {
return
}
return new EventSource(url)
}
const addEventListener = (name, callback) => {
let source = instance()
source.addEventListener(name, callback, false)
source.onerror = function(e) {
// EventSource failed
source.addEventListener(name, callback, false)
}
return source
}
const reListen = () => {
listeners.map((item) => {
addEventListener(item.name, item.callback)
})
}
const instance = () => {
// instantiate
if (instance != undefined) {
return instance
}
// create new
instance = create()
// hearbeat
setInterval(() => {
switch (instance.readyState) {
case instance.CONNECTING:
// wait and connecting
break;
case instance.CLOSED:
// re-create new when close
instance = create()
// re listen
reListen()
break;
}
}, timeout)
return instance
}
const addListener = (name, callback) => {
// sse add event listeners
let source = addEventListener(name, callback)
// for refresh purposes
listeners.push({
name,
callback,
})
return source
}
return {
url,
addListener,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment