Skip to content

Commit 0936421

Browse files
authored
Don't send unsubscribe msg when not connected (#126)
1 parent 7a6daf7 commit 0936421

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

lib/collection.ts

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,14 +26,13 @@ export const getCollection = <State>(
2626
let store = createStore<State>();
2727

2828
const refresh = () =>
29-
fetchCollection(conn).then(state => store.setState(state, true));
29+
fetchCollection(conn).then((state) => store.setState(state, true));
3030

3131
const refreshSwallow = () =>
3232
refresh().catch((err: unknown) => {
3333
// Swallow errors if socket is connecting, closing or closed.
3434
// We will automatically call refresh again when we re-establish the connection.
35-
// Using conn.socket.OPEN instead of WebSocket for better node support
36-
if (conn.socket.readyState == conn.socket.OPEN) {
35+
if (conn.connected) {
3736
throw err;
3837
}
3938
});
@@ -74,13 +73,13 @@ export const getCollection = <State>(
7473
if (!active) {
7574
// Unsubscribe from changes
7675
if (unsubProm)
77-
unsubProm.then(unsub => {
76+
unsubProm.then((unsub) => {
7877
unsub();
7978
});
8079
conn.removeEventListener("ready", refresh);
8180
}
8281
};
83-
}
82+
},
8483
};
8584

8685
return conn[key];

lib/connection.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,11 @@ export class Connection {
114114
return this.socket.haVersion;
115115
}
116116

117+
get connected() {
118+
// Using conn.socket.OPEN instead of WebSocket for better node support
119+
return this.socket.readyState == this.socket.OPEN;
120+
}
121+
117122
setSocket(socket: HaWebSocket) {
118123
const oldSocket = this.socket;
119124
this.socket = socket;
@@ -291,6 +296,10 @@ export class Connection {
291296
callback,
292297
subscribe: () => this.subscribeMessage(callback, subscribeMessage),
293298
unsubscribe: async () => {
299+
// No need to unsubscribe if we're disconnected
300+
if (!this.connected) {
301+
return;
302+
}
294303
await this.sendMessagePromise(messages.unsubscribeEvents(commandId));
295304
this.commands.delete(commandId);
296305
},

0 commit comments

Comments
 (0)