Skip to content

Commit 3334944

Browse files
author
Davi de Medeiros
committed
IMPROVEMENT: register socket's close event handler earlier instead of 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
1 parent 0c35ae3 commit 3334944

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

src/lib/create-or-join.ts

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,17 +17,21 @@ const cleanSubscribers = (
1717
) => {
1818
return () => {
1919
removeSubscriber(url, subscriber);
20+
21+
const socketLike = sharedWebSockets[url];
22+
23+
if (socketLike instanceof WebSocket) {
24+
socketLike.addEventListener('close', (event: WebSocketEventMap['close']) => {
25+
if (optionsRef.current.onClose) {
26+
optionsRef.current.onClose(event);
27+
}
28+
29+
subscriber.setReadyState(ReadyState.CLOSED);
30+
});
31+
}
32+
2033
if (!hasSubscribers(url)) {
2134
try {
22-
const socketLike = sharedWebSockets[url];
23-
if (socketLike instanceof WebSocket) {
24-
socketLike.onclose = (event: WebSocketEventMap['close']) => {
25-
if (optionsRef.current.onClose) {
26-
optionsRef.current.onClose(event);
27-
}
28-
setReadyState(ReadyState.CLOSED);
29-
};
30-
}
3135
socketLike.close();
3236
} catch (e) {
3337

@@ -83,7 +87,7 @@ export const createOrJoinSocket = (
8387
reconnectCount,
8488
reconnect: startRef,
8589
};
86-
90+
8791
addSubscriber(url, subscriber);
8892

8993
return cleanSubscribers(

0 commit comments

Comments
 (0)