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
