Supervisor
Supervisors are a fundamental concept in OTP. They monitor and manage the lifecycle of processes, restarting them if they fail.
Create a application using mix:
mix new counter --sup
lib/counter/application.ex
defmodule Counter.Application do
use Application
def start(_type, _args) do
children = [
{Counter, 0}
]
opts = [strategy: :one_for_one, name: Counter.Supervisor]
Supervisor.start_link(children, opts)
end
end
put the counter code into lib/counter.ex
defmodule Counter do
use GenServer
def init(initial_value) do
{:ok, initial_value}
end
# sync calls
def handle_call(:get_count, _from, state) do
{:reply, state, state}
end
# async calls
def handle_cast(:incr, state) do
{:noreply, state + 1}
end
# helper functions
def incr, do: GenServer.cast(__MODULE__, :incr)
def get_count, do: GenServer.call(__MODULE__, :get_count)
def start_link(initial_value) do
GenServer.start_link(__MODULE__, initial_value, name: __MODULE__)
end
end
iex -S mix
iex(1)> Counter.get_count
0
iex(2)> Counter.incr
:ok
iex(3)> Counter.get_count
1