Elixir Advanced Introduction
Elixir Advanced is the deeper study of building large, reliable systems in Elixir. It builds on the Beginner and Intermediate courses.
A worker holds state and answers a question
A GenServer keeps a value and answers calls with it. The counter starts at zero.
defmodule Counter do
use GenServer
def start_link(v), do: GenServer.start_link(__MODULE__, v)
def init(v), do: {:ok, v}
def handle_call(:get, _from, v), do: {:reply, v, v}
def handle_cast({:add, n}, v), do: {:noreply, v + n}
end
{:ok, counter} = Counter.start_link(0)
IO.inspect(GenServer.call(counter, :get))
GenServer.stop(counter)A cast changes state without a reply
A cast updates the value and returns at once. The next call sees the new value.
defmodule Counter do
use GenServer
def start_link(v), do: GenServer.start_link(__MODULE__, v)
def init(v), do: {:ok, v}
def handle_call(:get, _from, v), do: {:reply, v, v}
def handle_cast({:add, n}, v), do: {:noreply, v + n}
end
{:ok, counter} = Counter.start_link(10)
GenServer.cast(counter, {:add, 5})
IO.inspect(GenServer.call(counter, :get))
GenServer.stop(counter)A stopped worker is no longer alive
Stopping a worker ends its process. The liveness check then answers false.
defmodule Counter do
use GenServer
def start_link(v), do: GenServer.start_link(__MODULE__, v)
def init(v), do: {:ok, v}
def handle_call(:get, _from, v), do: {:reply, v, v}
def handle_cast({:add, n}, v), do: {:noreply, v + n}
end
{:ok, counter} = Counter.start_link(7)
GenServer.stop(counter)
IO.inspect(Process.alive?(counter))Example
defmodule Counter do
use GenServer
def start_link(v), do: GenServer.start_link(__MODULE__, v)
def init(v), do: {:ok, v}
def handle_call(:get, _from, v), do: {:reply, v, v}
def handle_cast({:add, n}, v), do: {:noreply, v + n}
end
{:ok, counter} = Counter.start_link(3)
GenServer.cast(counter, {:add, 4})
GenServer.cast(counter, {:add, 5})
IO.inspect(GenServer.call(counter, :get))
GenServer.stop(counter)
IO.inspect(Process.alive?(counter))Key points
- Prerequisite: the Beginner and Intermediate courses come first.
- Roadmap: the course covers advanced OTP, distribution, metaprogramming, behaviours and protocols, BEAM internals, resilience, state, testing, and projects.
- Depth: each lesson takes one idea further than its earlier version.
- Proof: every code block in the course runs for real and its output is checked.
- Focus: later lessons show how parts fail and how the system recovers.
In this example, the counter starts at 3, two casts add 4 and 5, a call shows 12, a stop ends the worker, and the liveness check shows false.
Note
advanced code still uses the same small building blocks from earlier courses.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the Elixir Advanced course build on?