improve signalR unsubscribe

This commit is contained in:
Фролов 2021-07-27 11:10:03 +05:00
parent 639ab50482
commit 5dc042d7be

View File

@ -48,6 +48,21 @@ type handlerFunction = (...args: any[]) => void;
type cleanFunction = (...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). /** Subscribe on some SignalR method (topic).
* @example useEffect(() => Subscribe('methodName', `${id}`, handleNewData), [id]); * @example useEffect(() => Subscribe('methodName', `${id}`, handleNewData), [id]);
* @param {string} methodName name of the method * @param {string} methodName name of the method
@ -66,12 +81,7 @@ const Subscribe = (
connection.on(methodName, handler) connection.on(methodName, handler)
}) })
if(groupName) return MakeUnsubscribeFunction(Connections[hubUrl],methodName,groupName)
return () => {
Connections[hubUrl].send('RemoveFromGroup', groupName)
.finally(()=>Connections[hubUrl].off(methodName))
}
return () => Connections[hubUrl].off(methodName)
} }
/** Invokes some SignalR method. /** Invokes some SignalR method.