I love RxJS! This blog post shows how to use RxJS websocket client that automatically reconnect on errors.

Server

Let’s create a simple websocket server that terminates connection every 10th message. This is simple node server that uses ws package.

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 7777 });



wss.on('connection', function connection(ws) {

let count = 0;

ws.on('message', function incoming(message) {

if (count === 10) {

ws.terminate();

} else {

ws.send(message);

count++;

}

});

});

RxJS Client

So now it is time to look at what RxJS provides to handle websockets. RxJS gives us webSocket subject that is a wrapper around the w3c-compatible WebSocket object provided by the browser. Here it is:

We can create a websocket connection in one simple line:

const subject = webSocket('ws://localhost:7777');

After the connection is create in order to send message to the server — just do next() on the subject like that:

subject.next('hi there');

To receive a message from the websocket, we can subscribe to the subject:

const subscription = subject

.asObservable()

.subscribe(data => observer.next(data),

error => observer.error(error),

() => observer.complete());

So we have all required blocks to create a websocket. Observable.create is used to wrap the logic into an observable. The sample code here also does emulation of sending message every 1 second using setInterval.

const createWebSocket = uri => {

return Observable.create(observer => {

try {

const subject = webSocket(uri);



const handler = setInterval(() => {

subject.next('hi there');

}, 1000);



const subscription = subject.asObservable()

.subscribe(data =>

observer.next(data),

error => observer.error(error),

() => observer.complete());



return () => {

clearInterval(handler);

if (!subscription.closed) {

subscription.unsubscribe();

}

};

} catch (error) {

observer.error(error);

}

});

};

Error handling with retryWhen

Now the RxJS websocket is ready to use. Since this is just an observable we can use any RxJS operator that deals with error handling. retryWhen may be a good option for us — to retry to open a websocket connection in case of the server terminates it.

Here is the code that use websocket observable and handle errors with retryWhen.