Does anybody know how to use phoenix_pubsub
as a standalone component?
I’d like to use it as a generic pubsub to communicate between some umbrella child applications.
Does anybody know how to use phoenix_pubsub
as a standalone component?
I’d like to use it as a generic pubsub to communicate between some umbrella child applications.
I did some digging around in the Phoenix channel code and was able to put this together.
Hopefully, it helps someone else.
defmodule Commander.Server do
use GenServer
#
# client
#
def dispatch(event) do
Phoenix.PubSub.broadcast(Commander.PubSub, get_event_name(event), event)
end
def subscribe(subscriber, event) do
GenServer.start_link(__MODULE__, { subscriber, event })
end
#
# callbacks
#
def init({ subscriber, event }) do
Phoenix.PubSub.subscribe(Commander.PubSub, event)
{ :ok, { subscriber } }
end
def handle_info(msg, { subscriber } = state) do
subscriber.handle(msg)
{ :noreply, state }
end
#
# private
#
defp get_event_name(event) do
event.__struct__
|> to_string()
|> String.replace("Elixir.", "")
end
end
It has been a while, but according to the latest Phoenix.PubSub (1.1.1), it also “also provides an API for direct usage”:
https://hexdocs.pm/phoenix_pubsub/Phoenix.PubSub.html#module-direct-usage