Thought Leadership
Jul 25, 2023

Use Angular WebSocketSubject to Save Bundle Space in this demo I built!

Streamline your real-time applications with seamless integration in your broader RxJS ecosystem
Use Angular WebSocketSubject to Save Bundle Space in this demo I built!

At NgConf 2023, I had the privilege of attending the advanced RxJS workshop led by industry experts Mike Ryan and Brian Love. WebSocketSubject particularly caught my attention among the various intriguing topics covered.

In my previous Angular projects, when I needed to implement WebSocket consumption, my initial instinct was to rely on third-party libraries. However, if I had been aware of WebSocketSubject earlier, it could have potentially saved valuable bundle space. Learning about this powerful feature was truly eye-opening.

What is Angular WebSocket for?

WebSocket is commonly used for various real-time applications, such as chat applications, multiplayer games, collaborative editing tools, stock market updates, and more, where instant data updates and bi-directional communication are required between clients and servers.

RxJS WebSocketSubject is an important feature in RxJS. It provides a powerful way to handle WebSocket communication in a reactive and observable manner. Here are some reasons why RxJS WebSocketSubject is important:

  1. Reactive and Observable Nature: RxJS is built around the concept of reactive programming, which focuses on the propagation of changes and events over time. With WebSocketSubject, you can create observables that represent the stream of messages received from a WebSocket connection. This allows you to apply reactive operators like map, filter, debounce, and merge to manipulate the data stream easily.
  2. Simplified WebSocket Management: WebSocketSubject abstracts away the low-level details of managing WebSocket connections, such as opening, closing, sending, and receiving messages. It provides a higher-level interface that simplifies WebSocket management and allows you to focus on the logic of handling incoming and outgoing messages.
  3. Bi-Directional Communication: WebSocketSubject supports bidirectional communication, allowing you to both send and receive messages over a WebSocket connection. You can subscribe to the WebSocketSubject to receive messages as they arrive and use methods like next() to send messages to the server. This bidirectional communication is crucial for real-time applications where instant updates and interactive data exchanges are required.
  4. Integration with RxJS Operators: RxJS provides a rich set of operators that can be applied to observables, allowing you to transform, filter, combine, and manipulate the WebSocket data stream. With WebSocketSubject, you can leverage these operators to handle complex scenarios like buffering, throttling, debouncing, error handling, and more. This makes it easier to implement advanced logic and handle various WebSocket-related scenarios effectively
  5. Error Handling and Retry Strategies: WebSocketSubject offers error handling capabilities, allowing you to handle errors that may occur during the WebSocket connection. You can catch and handle errors using RxJS operators like catchError or retry to implement retry strategies or fallback mechanisms in case of connection failures. This helps to ensure the stability and reliability of your WebSocket-based applications.
  6. Integration with Existing RxJS Ecosystem: RxJS WebSocketSubject seamlessly integrates with the broader RxJS ecosystem. You can combine WebSocket observables with other observables, use subjects, or apply other RxJS features to create more complex reactive workflows. This interoperability allows you to leverage the full power of RxJS for handling WebSocket communication within your applications

Example of an Angular WebSocket

In order to illustrate in a simplistic way how to handle web sockets in Angular I have created a simple app based on the get started guide from the Angular site. It consists of 2 components:

  • Top Bar: Includes a shopping cart icon with a number badge the idea is that every time the WebSocket notifies us that the user added a product it will increment the number in one.
  • Product List: Includes 2 buttons 1 for adding products to our shopping cart and 1 that will complete our web socket connection.

We also need a service to create our WebSocket subject. This service will be shared between the top bar and product list components.

The web socket subject needs a url config source and it could be a WebSocket end point or a WebSocket configuration object. In this reading we will focus on the first option you can explore further the configuration object by reading the docs.

I am using the postman echo api to simulate a response from a server web socket, postman echo will help us to get a response from a WebSocket with whatever input we provide.

Finally, let’s expose the WebSocket as an observable and keep our subject as private to avoid undesirable modifications.

Now in the add products component, let’s inject our WebSocket service and start pushing some info.

This component has two main actions, one is to Add a product which is basically telling our web socket echo service that a string “Add Product” needs to be ‘echoed’, it also includes a complete function that will close the connection with the WebSocket and no further messages are going to be sent.

Finally, the top bar component will be in charge of subscribing to the WebSocket and ‘listening’ for changes.

Now the component is subscribed to the observable we created earlier in the service phase, I specifically wanted to subscribe so you can see how your WebSocket observable is being handled. Every time the WebSocket emits a new value we are catching the count of how many times the Add Product button from the product list component is clicked.

In the view, the counter variable will update the shopping cart number batch.

If you want to stop receiving data from the WebService, you just need to complete it. In this example, you can do it by clicking the complete connection button from the product list component. Once you click this button and your connection is closed, if you click the add product button the badge number is not going to change because you already set the state of your WebSocket state as completed.

You can play with this demo here. Feel free to fork it and add more functionality.

Reference https://rxjs.dev/api/webSocket/webSocket#description

Conclusion:

RxJS WebSocketSubject provides a reactive and observable interface for WebSocket communication, simplifies WebSocket management, enables bi-directional communication, integrates with RxJS operators, offers error handling capabilities, and seamlessly integrates with the broader RxJS ecosystem.

These features make it a powerful tool for handling real-time, bidirectional data streams over WebSocket connections in a more elegant and manageable way.

. . .
About HeroDevs

HeroDevs partners with open-source authors to offer comprehensive solutions for sunsetted open-source software. Our Never-Ending Support products ensure businesses remain secure and compliant, even as their depended-upon open-source packages reach end-of-life. Alongside this, our elite team of software engineers and architects provides expert consulting and engineering services, assisting clients in migrating from deprecated packages and modernizing their technology stacks.

Article Summary
Unveil the power of RxJS WebSocketSubject at NgConf 2023 for managing WebSocket in Angular. Learn from experts how to optimize real-time communications.
Author
Abraham Huerta
Software Engineer
Related Articles
Executive Order 14028: Elevating National Cybersecurity
The White House's Call to Action for a Safer Digital Future Setting New Benchmarks for Global Cybersecurity Standards
PCI Compliance: What Every Business Owner Needs to Know
Understanding the Essentials of Payment Security and PCI DSS Integration
Navigating Drupal 7 End-of-Life: Your Options and HeroDevs' Never-Ending Support
Explore paths for Drupal 7 users, from upgrading to newer versions to leveraging ongoing support with HeroDevs.