Simple Reconnect Logic for RXJS websocket
Rxjs includes a websocket object, which is wrapper around the w3c-compatible WebSocket object provided by the browser. It returns a WebSocketSubject<T>
: Subject which allows to both send and receive messages via WebSocket connection.
Using RXJS and typescript, it’s easy to set up a websocket connection and subscribe to the websocket responses:
socket = webSocket<WebSocketRequestMessage | WebSocketResponseMessage>(URL)
socket.pipe().subscribe((message) => {
console.log(`message from the websocket: ${message}`)
}
However, what happens if this websocket gets disconnected? With the current set up, there is no attempt to reconnect. The websocket is not resilient. I was looking for solutions and found lots of implementations using retryWhen. Unfortunately, retryWhen is being depreciated.
However, retry can be used to build a system where if the connection is interrupted, a reconnection is attempted every 5 seconds. Below I pass a RetryConfig into retry to specify the number of times to retry and the delay interval between reconnection attempts:
socket = webSocket<WebSocketRequestMessage | WebSocketResponseMessage>(URL)
socket.pipe(
retry({count: 10, delay: 5000})
).subscribe((message) => {
console.log(`message from the websocket: ${message}`)
}
Hooray! Now the websocket will try to reconnect 10 times with a 5 second delay between each reconnection attempt.