Skip to content

Instantly share code, notes, and snippets.

@Noitidart
Created March 7, 2019 13:36
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 Noitidart/e829b34822389f6208840ae0a37ecc76 to your computer and use it in GitHub Desktop.
Save Noitidart/e829b34822389f6208840ae0a37ecc76 to your computer and use it in GitHub Desktop.
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