Hello!
I am working on building out a simple chat interface using LiveView and live components. My approach was to have each LC use Phoenix.PubSub.subscribe/broadcast
, as I was aiming for a simple drop-in component which didn’t require altering the parent LV state/etc.
However, I’ve found that calling Phoenix.PubSub.broadcast/3
from inside the LC seems to ignore the broadcast topic, triggering an event on the parent LV instead.
Here’s a (brief) code snippet to demonstrate:
# my_chat_component.ex
def mount(socket) do
Phoenix.PubSub.subscribe(Example.PubSub, "chat:id")
...
end
def handle_event("send_message", message, socket) do
Phoenix.PubSub.broadcast(Example.PubSub, "chat:id", {:chat_message, message})
...
end
def handle_info({:chat_message, data}, socket) do
# This does not fire!
...
end
In this code, I’d expect that any listener to topic chat:id
would be alerted with the :chat_message
data, and the local handle_info
would be called. However, when broadcast/3
is called, the local handle_info
is not fired, and an error raises from the parent (who is not even subscribed to the topic at all):
function ExampleWeb.ParentView.handle_info/2 is undefined or private
I’m pretty new to Phoenix/Elixir in general, so perhaps I am just using the wrong broadcast
or have the wrong mental model around how LC’s function as sub-processes to their LV parent? Maybe this is an actual bug in LV? I’m not sure. For what it’s worth, I am using PubSub features in other pieces of my application and it seems to work as expected, so this seems to be an LV<->LC issue.
Any help would be greatly appreciated. Thank you!