SignalR "withAutomaticReconnect" issue

75 Views Asked by At

How to dispose or destroy this withAutomaticReconnect after my condition is met? No matter what I try, the method executes every time.

const connection = new signalR.HubConnectionBuilder()
      .withUrl(socketServerUrl, {
        withCredentials: false,
        skipNegotiation: true,
        transport: signalR.HttpTransportType.WebSockets,
      })
      .withAutomaticReconnect({
        nextRetryDelayInMilliseconds: ({ elapsedMilliseconds }) => {
          // function content
        },
      })
      .configureLogging(signalR.LogLevel.Information)
      .build();

    if (isGameSessionExpired) {
      // Looking for something like that, but didn't work
      connection.stop();
      connection.withAutomaticReconnect(null);
      connection = null;
    }
1

There are 1 best solutions below

0
Jason Pan On BEST ANSWER

It's important to note that once a connection is declared as const, it can't be reassigned to null.

And I just optimized the code and everything works fine with me, you can try it.

let allowReconnect = true; // allow reconnect by default

const connection = new signalR.HubConnectionBuilder()
  .withUrl(socketServerUrl, {
    withCredentials: false,
    skipNegotiation: true,
    transport: signalR.HttpTransportType.WebSockets,
  })
  .withAutomaticReconnect({
    nextRetryDelayInMilliseconds: ({ elapsedMilliseconds }) => {
      if (!allowReconnect) {
        return null; // don't reconnect any more
      }
      // other logic here if you have
    },
  })
  .configureLogging(signalR.LogLevel.Information)
  .build();

if (isGameSessionExpired) {
  allowReconnect = false; // update the allowReconnect flag to prevent the reconnect behavior
  connection.stop(); // stop the connection
}