Name GenServer Processes
Learn how to name GenServer processes and subsequently each game process in the system.
We'll cover the following...
The issue so far
So far, we start new GenServer
processes and bind their PIDs to variables. Whenever we’ve needed to call a public function on a process, we’ve passed that variable in as the first argument. This clearly works, but it leaves us with a problem.
In a full application, we need to keep track of every variable for every process we start. We need to always keep them in scope, and clear individual variables out when their process stop. If that sounds really messy, that’s because it is.
It would be great if we could just name each process as we start it, and pass that name in whenever we want to call a function. It would be even better if we don’t have to remember the name, but are able to reconstruct it on the fly when needed. In an ideal scenario, these names would clear themselves out when their process stop.
Wishes can come true. Process registration does all this for us.
There are several ways to register GenServer
processes by name. Let’s explore them and see which fits our needs best.
New IEx session
We first specify a name as an atom and as the third argument to GenServer.start_link/3
.
Let’s run these commands in the terminal:
alias IslandsEngine.Game
GenServer.start_link(Game, "Frank", name: :islands_game)
We can use the raw GenServer.start_link/3
function here. We need to specify the module name instead of using __MODULE__
because this function call does not originate inside the Game
module the way it does in ...