Created
June 4, 2016 12:12
-
-
Save StevenXL/c41220983be32bc1809ae213b4fa13b7 to your computer and use it in GitHub Desktop.
Medium - Elixir Process Registry Tutorial Part 2
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 ProcessRegistry do | |
use GenServer | |
# Client API # | |
def start_link do | |
GenServer.start_link(__MODULE__, nil, name: :registry) | |
end | |
def register_name(key, pid) when is_pid(pid) do | |
GenServer.call(:registry, {:register_name, key, pid}) | |
end | |
# Server API # | |
def init(nil) do | |
{:ok, %{}} | |
end | |
def handle_call({:register_name, key, pid}, _from, registry) do | |
case Map.get(registry, key, nil) do | |
nil -> | |
Process.monitor(pid) | |
registry = Map.put(registry, key, pid) | |
{:reply, :yes, registry} | |
_ -> {:reply, :no, registry} | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment