Skip to content

Instantly share code, notes, and snippets.

@gausby
Last active October 29, 2015 14:21
Show Gist options
  • Select an option

  • Save gausby/57f6c21cbee469b5c475 to your computer and use it in GitHub Desktop.

Select an option

Save gausby/57f6c21cbee469b5c475 to your computer and use it in GitHub Desktop.
defmodule Name do
use GenServer
def start_link(data) do
GenServer.start_link(__MODULE__, data, name: via_name(data))
end
# do what ever you need to do with data
defp via_name(data),
do: {:via, :gproc, gproc_name(data)}
defp gproc_name(data),
do: {:n, :l, {__MODULE__, :something, data}}
# it is good to keep __MODULE__ in the registration name for later debugging in prod
# ... the rest of the GenServer implementation
end
@dch
Copy link
Copy Markdown

dch commented Oct 29, 2015

from twitter, not tested. The thing here is to use MODULE or similar to ensure your Gen* are cleanly separated in gproc. You probably want tighter restrictions on data (e.g. simple short binary or similar) to avoid refcount issues or just things getting too confusing :-)

defmodule Name do
  use GenServer

  def start_link(data) do
    registry = {:via, :gproc, {:n, :l, {__MODULE__, data}}}
    GenServer.start_link(__MODULE__, data, name: registry)
  end

  # ... the rest of the GenServer implementation
end

@dch
Copy link
Copy Markdown

dch commented Oct 29, 2015

I usually have a Name.start/1 call that either spawns a new GenServer if not already started, or returns pid of the existing one if found.

@gausby
Copy link
Copy Markdown
Author

gausby commented Oct 29, 2015

I like the idea of that. It simplifies the api a great deal when it comes to using it. 99% of the time I would like to just get the process.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment