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