Last active
March 24, 2016 20:34
-
-
Save felipeelias/d41f59592e91218e52bc to your computer and use it in GitHub Desktop.
PubSub server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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