Skip to content

Commit

Permalink
IMPROVEMENT: register socket's close event handler earlier instead of…
Browse files Browse the repository at this point in the history
… on last unsubscription

also use addEventListener instead of reassigning and losing the previous socket-like close handlers

this was causing a bug where only the first subscriber of a shared socket would have its handler invoked,
since its listener was only being registered when cleaning unsubscribers for the last subscription for a url
  • Loading branch information
Davi de Medeiros committed Dec 20, 2021
1 parent a0ab1b7 commit 2dfe379
Showing 1 changed file with 14 additions and 10 deletions.
24 changes: 14 additions & 10 deletions src/lib/create-or-join.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,21 @@ const cleanSubscribers = (
) => {
return () => {
removeSubscriber(url, subscriber);

const socketLike = sharedWebSockets[url];

if (socketLike instanceof WebSocket) {
socketLike.addEventListener('close', (event: WebSocketEventMap['close']) => {
if (optionsRef.current.onClose) {
optionsRef.current.onClose(event);
}

subscriber.setReadyState(ReadyState.CLOSED);
});
}

if (!hasSubscribers(url)) {
try {
const socketLike = sharedWebSockets[url];
if (socketLike instanceof WebSocket) {
socketLike.onclose = (event: WebSocketEventMap['close']) => {
if (optionsRef.current.onClose) {
optionsRef.current.onClose(event);
}
setReadyState(ReadyState.CLOSED);
};
}
socketLike.close();
} catch (e) {

Expand Down Expand Up @@ -83,7 +87,7 @@ export const createOrJoinSocket = (
reconnectCount,
reconnect: startRef,
};

addSubscriber(url, subscriber);

return cleanSubscribers(
Expand Down

0 comments on commit 2dfe379

Please sign in to comment.