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.