Tracking Real-Time Results
Let'searn how to perform real-time event handling using PubSub.
First on the agenda is automatically updating the survey results chart component when a user completes a survey. Right now, users are entering demographics and survey results through the RatingLive.FormComponent
. When
we handle the event for a new survey rating in the parent SurveyLive
LiveView, we need to notify AdminDashboardLive
. The question is how.
We could try to do so with a direct message, but we’d need access to the
AdminDashboardLive
PID. Even if we had access, this view could crash and the PID would change. We could give names to the AdminDashboardLive
process, but that would require more work and more synchronization. Fortunately, there’s a better way.
Implementation of the Publish/Subscribe
pattern
We’re going to use Phoenix PubSub, a publish/subscribe
implementation, to build the feature. Under the hood, a LiveView is just a process. publish/subscribe is a common pattern for sending messages between processes in which messages are broadcast over a topic to dedicated subscribers listening to that topic. Let’s see how it works.
Rather than sending a message directly from a sender to a receiver with send/2
, we’ll use a Phoenix PubSub server as an intermediary. Processes that need access to a topic announce their interest with a subscribe/1
function. Then, sending processes broadcast a message through the PubSub service, over a given topic, which forwards the message to all subscribed processes.
This service is exactly what we need in order to pass messages between LiveViews. Going through an intermediary is perfect for this use case. Neither SurveyLive
nor AdminDashboardLive
need to know about one another. They need only know about a common PubSub topic. That’s good news. All we need to do is use the PubSub.broadcast/3
function to send a message over a particular topic and the PubSub.subscribe/1
function to receive a message over a particular topic.
Planning the feature
Our AdminDashboardLive
process will use Phoenix PubSub to subscribe to a topic.
This means that AdminDashboardLive
will receive messages broadcast over that topic from anywhere else in our application. For our new feature, we’ll broadcast “new survey results” messages from the SurveyLive
LiveView. Then, we’ll teach AdminDashboardLive
how to handle these messages by updating the
SurveyResultsLive
component with the new survey results info.
By combining LiveView’s real-time functionality with PubSub’s ability to pass messages across a distributed set of clients, we can seamlessly keep our LiveViews up-to-date.
With that plan, we’re ready to write some code. We’ll start with a brief look at how PubSub is configured in your Phoenix application. Then, we’ll set up our message broadcast and subscribe workflow. Finally, we’ll teach the AdminDashboardLive
how to update its SurveyResultsLive
child component.
Get hands-on with 1400+ tech skills courses.