From c6c07fd0b1c0ceb46a9c6f54783d8669be9d8b05 Mon Sep 17 00:00:00 2001 From: Jan Rollmann Date: Wed, 4 Oct 2023 15:01:41 +0200 Subject: [PATCH] Fix memory leak on Ux4iot initialization --- src/library/Ux4iotContext.tsx | 1 + src/library/base/Ux4iot.ts | 13 ++++++++++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/library/Ux4iotContext.tsx b/src/library/Ux4iotContext.tsx index f0a48d5..1095c69 100644 --- a/src/library/Ux4iotContext.tsx +++ b/src/library/Ux4iotContext.tsx @@ -53,6 +53,7 @@ export const Ux4iotContextProvider: ComponentType = ({ initialize(); return () => { + Ux4iot.destroyInitialization(); if (ux4iot) { ux4iot.destroy(); setUx4iot(undefined); diff --git a/src/library/base/Ux4iot.ts b/src/library/base/Ux4iot.ts index ceace92..e0216b2 100644 --- a/src/library/base/Ux4iot.ts +++ b/src/library/base/Ux4iot.ts @@ -73,6 +73,7 @@ export class Ux4iot { retryTimeout: number; maxRetryTimeout: number; retryTimeoutAfterError?: NodeJS.Timeout; + static initializationTimeout?: NodeJS.Timeout; onSocketConnectionUpdate?: ConnectionUpdateFunction; onSessionId?: (sessionId: string) => void; @@ -101,11 +102,10 @@ export class Ux4iot { const timeout = reconnectTimeout ?? RECONNECT_TIMEOUT; const maxTimeout = maxReconnectTimeout ?? MAX_RECONNECT_TIMEOUT; const api = new Ux4iotApi(options); - let initializationTimeout: NodeJS.Timeout | undefined; try { const sessionId = await api.getSessionId(); api.setSessionId(sessionId); - clearTimeout(initializationTimeout); + clearTimeout(Ux4iot.initializationTimeout); return new Ux4iot(options, sessionId, api, onSessionId); } catch (error) { const [reason, description] = NETWORK_STATES.UX4IOT_OFFLINE; @@ -122,13 +122,20 @@ export class Ux4iot { }; return new Promise((resolve, reject) => { - initializationTimeout = setTimeout(() => { + Ux4iot.initializationTimeout = setTimeout(() => { return resolve(Ux4iot.create(nextOptions, onSessionId)); }, timeout); }); } } + public static destroyInitialization() { + if (Ux4iot.initializationTimeout) { + console.warn('Initialization interval canceled'); + clearTimeout(Ux4iot.initializationTimeout); + } + } + private initializeSocket() { const socketURI = this.api.getSocketURL(this.sessionId); this.socket = io(socketURI, { transports: ['websocket', 'polling'] });