Created
March 7, 2019 13:36
-
-
Save Noitidart/e829b34822389f6208840ae0a37ecc76 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
class SocketActivity { | |
static get Status() { | |
return { | |
CONNECT: 'connect', | |
DISCONNECT: 'disconnect', | |
RECONNECT: 'reconnect' | |
}; | |
} | |
constructor() { | |
if (SocketActivity.singleton) return SocketActivity.singleton; | |
SocketActivity.singleton = this; | |
this.handleConnect = this.handleConnect.bind(this); | |
this.handleDisconnect = this.handleDisconnect.bind(this); | |
this.handleReconnect = this.handleReconnect.bind(this); | |
io.socket.on('connect', this.handleConnect); | |
io.socket.on('disconnect', this.handleDisconnect); | |
io.socket.on('reconnect', this.handleReconnect); | |
this.handlers = []; | |
} | |
notify(status) { | |
console.log(status.toUpperCase(), 'happened'); | |
for (let i = 0; i < this.handlers.length; i++) { | |
const handler = this.handlers[i]; | |
if (handler.status === status) { | |
handler.resolve(); | |
this.handlers.splice(i, 1); | |
i--; | |
} | |
} | |
} | |
handleConnect() { | |
// console.log('CONNECTED'); | |
this.notify(SocketActivity.Status.CONNECT); | |
} | |
handleDisconnect() { | |
// console.log('DISconnected'); | |
this.notify(SocketActivity.Status.DISCONNECT); | |
} | |
handleReconnect() { | |
// console.log('RESconnected'); | |
this.notify(SocketActivity.Status.RECONNECT); | |
this.notify(SocketActivity.Status.CONNECT); | |
} | |
static disconnect() { | |
const { singleton, Status } = SocketActivity; | |
const promise = new Promise(resolve => singleton.handlers.push({ | |
status: Status.DISCONNECT, | |
resolve | |
})); | |
console.log('will disconnect, then wait for disconnect'); | |
io.socket.disconnect(); | |
return promise; | |
} | |
static reconnect() { | |
const { singleton, Status } = SocketActivity; | |
const promise = new Promise(resolve => singleton.handlers.push({ | |
status: Status.CONNECT, | |
resolve | |
})); | |
console.log('will reconnect, then wait for connect'); | |
io.socket.reconnect(); | |
return promise; | |
} | |
static tillConnected() { | |
const { singleton, Status } = SocketActivity; | |
const promise = new Promise(resolve => singleton.handlers.push({ | |
status: Status.CONNECT, | |
resolve | |
})); | |
console.log('waiting for connect'); | |
return promise; | |
} | |
static tillDisconnected() { | |
const { singleton, Status } = SocketActivity; | |
const promise = new Promise(resolve => singleton.handlers.push({ | |
status: Status.DISCONNECT, | |
resolve | |
})); | |
console.log('waiting for disconnect'); | |
return promise; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment