30 lines
946 B
Elixir
30 lines
946 B
Elixir
defmodule ExSpeedGame.PubSub do
|
|
@moduledoc """
|
|
Light pubsub system based on Registry so that processes can listen to state publishes from
|
|
others.
|
|
|
|
Processes must be GenServers and respond to state request.
|
|
"""
|
|
|
|
@spec subscribe(atom | pid) :: term
|
|
def subscribe(target) when is_atom(target) or is_pid(target) do
|
|
target = if is_atom(target), do: Process.whereis(target), else: target
|
|
|
|
{:ok, _} = Registry.register(__MODULE__, target, nil)
|
|
GenServer.call(target, {:esg_pubsub, :get_state})
|
|
end
|
|
|
|
@spec publish(any) :: :ok
|
|
def publish(data) do
|
|
Registry.dispatch(__MODULE__, self(), fn entries ->
|
|
for {pid, _} <- entries, do: send(pid, {:esg_pubsub, :pub, data})
|
|
end)
|
|
end
|
|
|
|
@spec clear(atom | pid) :: :ok
|
|
def clear(target) when is_atom(target) or is_pid(target) do
|
|
target = if is_atom(target), do: Process.whereis(target), else: target
|
|
|
|
:ok = Registry.unregister(__MODULE__, target)
|
|
end
|
|
end
|