Build a Supervisor for the Game

Learn how to build a supervisor for our game processes.

Starting with a custom supervisor

Now that we have the Game module’s child specification showing the values we want, we’re ready to create a custom supervisor. We explore two ways to do this. One is as simple as starting a supervisor process with the right options. The other involves creating a new module that contains the callbacks we need and also some helper functions we want.

Each game in the Islands is a separate GenServer process. These processes come and go as players start new games and then end them. We need a supervisor specifically to monitor games, and the :simple_one_for_one strategy is perfect for processes we need to start and stop at runtime.

Most of the work of creating a custom supervisor happens when starting a new supervisor process with the right options. After that, the supervisor process itself does the rest. There are two ways to do this.

The most straightforward way is with the Supervisor.start_link/2 function. start_link/2 takes a list of child modules to start and also takes a list of options. In our case, this would be the Game module and the :simple_one_for_one strategy.

We could also include new values for :max_restarts or :max_seconds in the list of options as well, but their default values are fine for our purposes.

The first thing that Supervisor.start_link/2 does is get the child specification from any modules we specify. Because of that, we could pass in a list of child specifications instead. However, we’ve already customized the specification for the Game module, so we can just pass in the module name.

New IEx session

Let’s open up an IEx session to see how that works:

Get hands-on with 1200+ tech skills courses.