defmodule Podbox.PubSub do @moduledoc """ A wrapper around a registry for PubSub. """ @doc false @spec child_spec(any) :: Supervisor.child_spec() def child_spec(_) do Registry.child_spec( keys: :duplicate, name: __MODULE__, partitions: System.schedulers_online() ) end @doc "Subscribe to a topic" @spec subscribe(String.t(), Keyword.t()) :: :ok | {:error, any} def subscribe(topic, _opts \\ []) do with {:ok, _} <- Registry.register(__MODULE__, topic, nil) do :ok end end @doc "Unsubscribe from a topic" @spec unsubscribe(String.t()) :: :ok | {:error, any} def unsubscribe(topic) do Registry.unregister(__MODULE__, topic) end @doc "Broadcast a message to a topic" @spec broadcast(String.t(), any, any) :: :ok | {:error, any} def broadcast(topic, _event \\ nil, message) do Registry.dispatch(__MODULE__, topic, fn entries -> for {pid, _} <- entries, do: send(pid, {topic, message}) end) end end