Ok, examples:
You provide process for user to start
For example you have GenServer
that will send broadcast message each second:
defmodule MyLib.Sender do
use GenServer
def start_link(opts) do
pubsub = Keyword.fetch!(opts, :pubsub)
GenServer.start_link(__MODULE__, pubsub)
end
def init(pubsub), do: {:ok, pubsub, {:continue, :send}}
def handle_info(:ping, state), do: {:noreply, state, {:continue, :send}}
def handle_continue(:send, pubsub) do
Phoenix.PubSub.broadcast!(pubsub, "lib-channel", "new_message")
Process.send_after(self(), :ping, 1000)
{:noreply, pubsub}
end
end
And now your user will need to add {MyLib.Sender, pubsub: MyApp.Endpoint}
to their supervision tree, and everything will work as expected.
You provide function
If you have something like:
def foo do
endpoint = Application.get_env(:my_library, :app_endpoint)
endpoint.broadcast!("lib-channel", "new_message", [])
end
Then you can just do:
def foo, do: "new_message"
And force user to dispatch it on their own, or:
def foo(pubsub) do
Phoenix.PubSub.broadcast!(pubsub, "lib-channel", "new_message")
end