Skip to content

Instantly share code, notes, and snippets.

@felipeelias
Last active March 24, 2016 20:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felipeelias/d41f59592e91218e52bc to your computer and use it in GitHub Desktop.
Save felipeelias/d41f59592e91218e52bc to your computer and use it in GitHub Desktop.
PubSub server
defmodule Pubsub do
use Application
def start(_type, _options) do
import Supervisor.Spec
IO.puts("Initializing Pubsub app on #{inspect self}")
children = [
worker(Pubsub.Server, [], [name: :server_supervisor])
]
{:ok, pid} = Supervisor.start_link(children, strategy: :one_for_one)
end
end
defmodule Pubsub.Server do
use GenServer
def start_link do
GenServer.start_link(__MODULE__, [], name: {:global, __MODULE__})
end
def subscribe(pid) do
GenServer.call({:global, __MODULE__}, {:subscribe, pid})
end
def publish(message) do
GenServer.call({:global, __MODULE__}, {:publish, message})
end
def handle_call({:subscribe, pid}, _from, existing) do
subscribers = [pid | existing]
{:reply, :ok, subscribers}
end
def handle_call({:publish, message}, _from, subscribers) do
Enum.each(subscribers, fn subs -> send(subs, message) end)
{:reply, message, subscribers}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment