liveBook · Manning

Init/1

As explained in Elixir in Action, Third Edition

init/1 is the callback that receives startup data and returns a supervisor's child specifications and options.

init/1 is a startup callback whose contract depends on the OTP behaviour using it. In a GenServer, it receives the startup argument and returns {:ok, initial_state}; in a Supervisor, it returns child specifications and supervisor options. GenServer.start waits for initialization to finish, so startup work in init/1 directly affects the caller. section 6.2.3 section 8.3.5

Use the callback according to the behaviour being implemented:

  • Implement init(_) in a GenServer to establish the state passed to later handle_call/3 and handle_cast/2 callbacks. section 6.2.6
  • Implement init(_) in a Supervisor to describe children through Supervisor.init/2 and select options such as :one_for_one. section 8.3.5
  • Perform extra supervisor initialization here only when the additional control justifies the extra callback-module boilerplate. section 8.3.5

Supervisor callback module

defmodule Todo.System do use Supervisor def start_link do Supervisor.start_link(__MODULE__, nil) end def init(_) do Supervisor.init([Todo.Cache], strategy: :one_for_one) end end Supervisor.start_link/2 passes nil to init/1, which returns the supervisor specification for Todo.Cache. section 8.3.5

defmodule Todo.System do
  use Supervisor                                           #1
 
  def start_link do
    Supervisor.start_link(__MODULE__, nil)                 #2
  end
 
  def init(_) do                                           #3
    Supervisor.init([Todo.Cache], strategy: :one_for_one)  #3
  end                                                      #3
end

Inspect the complete callback-module form, including use Supervisor, startup delegation, and Supervisor.init/2. section 8.3.5

How Elixir in Action, Third Edition covers it

How deep it goes
Defines return contracts and lifecycle effects, while deferring detailed callback behavior and supervision-tree mechanics.
Examples
Uses a KeyValueStore GenServer and a Todo.System supervisor to demonstrate state initialization and child-tree configuration.
What it assumes
Assumes familiarity with Elixir modules, GenServer.start/2, Supervisor.start_link/2, and callback-based OTP processes.
What you can do after
Configure GenServer state or build a supervisor specification through a behaviour callback.
How it connects
Connects GenServer, Supervisor, child specifications, supervision trees, and callback modules.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.