Skip to content
This repository has been archived by the owner on Dec 13, 2020. It is now read-only.

Handle socket reconnections asynchronously and gracefully #1290

Merged
merged 1 commit into from
Oct 20, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 31 additions & 14 deletions src/actions/WindowActions.js
Original file line number Diff line number Diff line change
Expand Up @@ -982,20 +982,37 @@ export function collapsedMap(
}

export function connectWS(topic, cb) {
(this.sockClient && this.sockClient.connected) &&
this.sockClient.disconnect();

this.sock = new SockJs(config.WS_URL);
this.sockClient = Stomp.Stomp.over(this.sock);
this.sockClient.debug = null;
this.sockClient.connect({}, () => {
this.sockClient.subscribe(topic, msg => {
cb(JSON.parse(msg.body));
});
});
const subscribe = ({ tries = 3 } = {}) => {
if (this.sockClient.connected || tries <= 0) {
this.sockSubscription = this.sockClient.subscribe(topic, (msg) => {
cb(JSON.parse(msg.body));
});
} else {
// not ready yet
setTimeout(() => { subscribe({ tries: tries - 1 }); }, 200);
}
};
const connect = () => {
this.sock = new SockJs(config.WS_URL);
this.sockClient = Stomp.Stomp.over(this.sock);
this.sockClient.debug = null;
this.sockClient.connect({}, subscribe);
}
const connected = disconnectWS.call(this, connect);

if (!connected) {
connect();
}
}

export function disconnectWS() {
(this.sockClient && this.sockClient.connected) &&
this.sockClient.disconnect();
export function disconnectWS(callback) {
const connected = this.sockClient && this.sockClient.connected &&
this.sockSubscription;

if (connected) {
this.sockSubscription.unsubscribe();
this.sockClient.disconnect(callback);
}

return connected;
}