Add Real-time Out-of-stock Alerts
Learn how to add real-time alerts in our application using PubSub.
Real-time alerts
The last feature to add to our shopping cart is out-of-stock alerts. A shopping cart consists of a set of items that a shopper has added. The shopping cart will notify the shopper when any items go out of stock. If we remember from the CartView
module, an item will be determined to be available or not each time the cart is rendered—all that we need to do is trigger the cart to be rendered and sent to the connected client.
We’ll leverage PubSub to know when the ShoppingCartChannel
needs to send a message to the client. Our PubSub usage so far in this course has been tied to Channels—we’ve always pushed directly to a Channel topic. We can take a different approach, though. We’ll walk through how to subscribe to a PubSub topic that is not the same as a Channel topic.
Using dynamic PubSub subscriptions
Processes can subscribe and unsubscribe to messages for any PubSub topic. A process can subscribe to as many topics as it wants to. We will use this to build out-of-stock notifications. Each item will have a topic in the format item_out:{id}
and will broadcast messages in the format {:item_out, id}
.
The ShoppingCartChannel
needs to subscribe to the correct items, so it gets alerted regarding only the items it cares about, which helps improve the performance of live updates. It also needs to unsubscribe to items that are removed from the cart to stop getting notified about them. The following figure shows the steps that our Channel will follow:
Get hands-on with 1400+ tech skills courses.