From 5dc042d7be520aea5731f14de81b48682bc2565d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A4=D1=80=D0=BE=D0=BB=D0=BE=D0=B2?= Date: Tue, 27 Jul 2021 11:10:03 +0500 Subject: [PATCH] improve signalR unsubscribe --- src/services/signalr/index.ts | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/services/signalr/index.ts b/src/services/signalr/index.ts index 449cd65..72ed2fb 100644 --- a/src/services/signalr/index.ts +++ b/src/services/signalr/index.ts @@ -48,6 +48,21 @@ type handlerFunction = (...args: any[]) => void; type cleanFunction = (...args: any[]) => void; +const MakeUnsubscribeFunction = ( + connection: HubConnection, + methodName: string, + groupName: (string|null)):cleanFunction => { + return async() => { + if(connection.state === HubConnectionState.Connected) + { + if(groupName) + await connection.send('RemoveFromGroup', groupName) + connection.off(methodName) + } + connection.stop() + } +} + /** Subscribe on some SignalR method (topic). * @example useEffect(() => Subscribe('methodName', `${id}`, handleNewData), [id]); * @param {string} methodName name of the method @@ -66,12 +81,7 @@ const Subscribe = ( connection.on(methodName, handler) }) - if(groupName) - return () => { - Connections[hubUrl].send('RemoveFromGroup', groupName) - .finally(()=>Connections[hubUrl].off(methodName)) - } - return () => Connections[hubUrl].off(methodName) + return MakeUnsubscribeFunction(Connections[hubUrl],methodName,groupName) } /** Invokes some SignalR method.