Earlier this year, I covered the different types of RxJs subjects. There is another kind of Subject that I haven’t touched on yet: WebSocketSubject
.
What is a websocket?
It’s a mechanism to establish and maintain a two-way connection between a client and a server on the web. This means that with websockets you can:
- Receive real-time updates from a server
- Send real-time updates to a server
There are several different use cases for websockets, such as: Real-time chat applications, online gaming, stock trading, and IoT applications.
How to create a websocket with RxJs?
All we need is the webSocket
function from RxJs:
Note that the protocol is ws
and not http
. The above example assumes that our server accepts Websocket connections on port 8000. You can find a small example of such server-side code written with Node.js here.
To receive data from a WebSocketSubject, all we have to do is subscribe to it:
And if we want to send data to the server, we use the .next()
method, which behaves differently from the one in the other types of Subjects:
Now you know how RxJs provides a straightforward implementation for handling Websockets using a specific type of Subject.