Initializing GenServer State
Until now, we’ve relied directly on GenServer’s built-in start_link/3 function for starting new processes. This works, but we can do better.
When we run GenServer.start_link(Game, <initial state>), the idea that we’re starting a new game process is buried in the arguments. It would be much clearer if we could bring the Game module out front by writing Game.start_link(<initial state>).
To do this, we’ll follow the GenServer pattern—define a public function that wraps a GenServer module function that triggers a callback.
Let’s start with a public start_link/1 function in the Game module and have it wrap the GenServer.start_link/3 function. One player will start the game, and the second will join later. Let’s have ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access