dotnet / dotnet/aspnetcore

[SignalR][Client][TS] Unable to unsubscribe from SignalR connection state change events

Open
#59,626 3 comments 3 reactions 0 assignees View on GitHub
api-suggestion area-signalr
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

### Is there an existing issue for this?

- [x] I have searched the existing issues

### Is your feature request related to a problem? Please describe the problem.

I am integrating SignalR into my React code. Currently, there is no way to listen to all connection state changes.
A workaround I found is to use `onclose`, `onreconnecting` and `onreconnected`. However, there is no way to unsubscribe from these events.

On the client code, I preserve and reuse the connection instance. When a component needs to access the SignalR connection, it will get the same connection instance if one has already been created, and then subscribe to the changes.
When the component unmounts, it has no way to unsubscribe so the stale handlers are stuck in the connection instance(`this._closedCallbacks`, `this._reconnectingCallbacks`, and `this._reconnectedCallbacks`). When the component is remounted, new handlers are added. This causes memory leak on the client side.

### Describe the solution you'd like

- Add a way to unsubscribe from connection status change events. For example,
- Returns the unsubscribe function when calling `onclose`, `onreconnecting`, and `onreconnected` (Preferred, the consumer doesn't have to cache the callback reference manually).
- Or provides `offclose`, `offreconnecting`, and `offreconnected` (the naming can be changed).
- Or add a new method `onConnectionStateChange` which will be fired every time `this._connectionState` changes and do one of the following,
- Returns the unsubscribe function (Preferred, the consumer doesn't have to cache the callback reference manually).
- Or provides `offConnectionStateChange` (the naming can be changed).

### Additional context

The issue can be addressed by updating this file `src/SignalR/clients/ts/signalr/src/HubConnection.ts`

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.