Search⌘ K
AI Features

Initialize the GenServer State

Explore how to initialize the GenServer state in the Game module by defining a public start_link function that wraps GenServer.start_link. Understand how to model the game state with player data and rules, and see how Elixir's OTP pattern simplifies managing concurrent stateful processes.

We'll cover the following...

GenServer in the game.ex module

Until now, we’ve relied directly on the built-in start_link/3 function from GenServer to start new processes. However, 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 follow the GenServer pattern and define a public function that wraps a GenServer module function. This module function then 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 ...