Send an event to a Channel from outside Phoenix
So this one was non-obvious to me.
In the following example, any module on any process can call TopicChannel.send_to_channel/1
and that will be handled by the handle_info
call below and sent to the socket.
defmodule MyAppWeb.TopicChannel do
use Phoenix.Channel
def send_to_channel(data) do
Phoenix.PubSub.broadcast(
MyApp.PubSub,
"topic:subtopic",
%{type: "action", payload: %{data: data}
)
end
def join("topic:subtopic", message, socket) do
{:ok, socket}
end
def handle_info(%{type: "action"}=info, socket) do
push socket, "action", info
{:noreply, socket}
end
end
Tweet