Skip to content

Instantly share code, notes, and snippets.

@StevenXL
Created June 4, 2016 12:12
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 StevenXL/c41220983be32bc1809ae213b4fa13b7 to your computer and use it in GitHub Desktop.
Save StevenXL/c41220983be32bc1809ae213b4fa13b7 to your computer and use it in GitHub Desktop.
Medium - Elixir Process Registry Tutorial Part 2
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