Fix leaking connections

This commit is contained in:
Thomas Nordquist
2019-02-23 22:34:32 +01:00
parent 953422dcd4
commit 174eb0c767

View File

@@ -21,13 +21,18 @@ export class ConnectionManager {
public manageConnections() {
backendEvents.subscribe(addMqttConnectionEvent, this.handleConnectionRequest)
backendEvents.subscribe(removeConnection, (connectionId: string) => {
backendEvents.unsubscribeAll(makePublishEvent(connectionId))
this.removeConnection(connectionId)
})
}
private handleConnectionRequest = (event: AddMqttConnection) => {
const connectionId = event.id
// Prevent double connections when reloading
if (this.connections[connectionId]) {
this.removeConnection(connectionId)
}
const options = event.options
const connection = new MqttSource()
this.connections[connectionId] = connection
@@ -56,18 +61,19 @@ export class ConnectionManager {
})
}
public removeConnection(hash: string) {
const connection = this.connections[hash]
public removeConnection(conenctionId: string) {
const connection = this.connections[conenctionId]
if (connection) {
backendEvents.unsubscribeAll(makePublishEvent(conenctionId))
connection.disconnect()
delete this.connections[hash]
delete this.connections[conenctionId]
connection.stateMachine.onUpdate.removeAllListeners()
}
}
public closeAllConnections() {
Object.keys(this.connections)
.forEach(hash => this.removeConnection(hash))
.forEach(conenctionId => this.removeConnection(conenctionId))
}
}