3

In my app I have a few screens that use signalR like that. That function is called useEffect function and it works:

const setupSignalR = () =>
{
    SecureStore.getItemAsync("token").then(tk => {
            let connection = new HubConnectionBuilder()
            .withUrl("URL", {
            accessTokenFactory: () => tk
            })
            .build();

            connection.on("Update", function (message) {
             //DOSTUFF
            });

            connection.start()
            .then(() => console.log("connection started"))
            .catch(err => console.log("connecting hub failed err is : ", err));
    });
}

The problem is that if I leave the screen the connection stays open, and when I return to the screen I open another connection which means I now have 2 connections open at the same time. I know that signalR has a stop function that I can call, so I tried to use the navigation listeners like that, but they aren't called:

useEffect(() => 
{
    Load();
    setupSignalR();
    const unsubscribe = navigation.addListener('focus', () => {
        
      });
    const sub = navigation.addListener('blur', () => {
        console.log("============");
    });
}, [navigation]);

I generally leave a screen by pressing the back-button or by using navigation.navigate();

Kiril1512
  • 3,231
  • 3
  • 16
  • 41
user9210692
  • 193
  • 1
  • 10

2 Answers2

3
return () => {
    connection.stop();
}

Works.

Kiril1512
  • 3,231
  • 3
  • 16
  • 41
user9210692
  • 193
  • 1
  • 10
0

to me it is better not to put your 'connection.build' in each of you screens. it is recommended to set it somewhere in starts of you project. then you can listen to events in screens and handle them.

and for any reason like user logout, you can stop the connection