I've created a rest generic service which additionally consume a websocket per resource my websocket code looks like so:
initialize(hubSubRoute: string): void{
const accessToken = this.authManager.getRawAccessToken();
let hubUrl = environment.baseUrl + hubSubRoute;
if (accessToken) {
hubUrl += '?' + this.hubAuthorizationQueryParameter +'=' + accessToken;
}
this._hubConnection = new HubConnectionBuilder()
.withUrl(hubUrl)
.build();
}
startConnection(): void {
this._hubConnection.start()
.then(() => {
console.log('Hub connection started');
this.connectionEstablished.emit(true);
})
.catch(err => {
console.log('Error while establishing connection');
});
}
I know web-sockets are long lived connection. I'm wondering the best practices for maintaining their longevity. For example I have a messages services. Which will open a websocket and post message as they come, in, However,
If the user navigates away from that conversation, should I leave the web-socket open?
Or Should I close it and when the user returns back to that conversation, just obtain the missing messages and reinitialize the web-socket?