THE GenServer! Version 1.0!
CHEATSHEET
Initialization
def start_link(opts \\ []) do! Returns
CLIENT
GenServer.start_link(__MODULE__, :ok, opts)! {:ok, pid}!
end!
def init(:ok) do! {:ok, state} !
RETURN VALUES
CALLBACK
state = init_state()! {ok, state, 5_000} !
{:ok, state}! {:ok, state, :hibernate}!
end! {:stop, reason*} !
:ignore!
Synchronous Operation
def sync_op(pid, args) do!
CLIENT
GenServer.call(pid, {:sync_op, args})!
end!
def handle_call({:sync_op, args}, from, state) do!
CALLBACK
new_state = f(state, args)!
{:reply, new_state}!
end!
{:reply, reply, new_state}!
{:reply, reply, new_state, 5_000}!
{:reply, reply, new_state, :hibernate}!
RETURN VAL
!
{:noreply, new_state}!
{:noreply, new_state, 5_000}!
{:noreply, new_state, :hibernate}!
{:stop, reason*, reply, new_state}!
{:stop, reason*, new_state}!
Asynchronous Operation
def async_op(pid, args) do!
CLIENT
GenServer.cast(pid, {:async_op, args})!
end!
def handle_cast({:async_op, args}, state) do!
CALLBACK
new_state = f(state, args)!
{:noreply, new_state}!
end!
{:noreply, new_state}!
RETURN VAL
{:noreply, new_state, 5_000}!
{:noreply, new_state, :hibernate}!
{:stop, reason*, new_state} !
Copyright Benjamin Tan Wei Hao. Free to use without modication for non-commercial applications.
THE GenServer! Version 1.0!
CHEATSHEET
Out of band messages
CALLBACK def handle_info(msg, state) do!
new_state = f(state, msg)!
{:noreply, new_state}!
end!
{:noreply, new_state}!
RETURN VAL
{:noreply, new_state, 5_000}!
{:noreply, new_state, :hibernate}!
{:stop, reason*, new_state} !
Termination
def stop(pid, reason \\ :normal, timeout \\ :infinity) do!
CLIENT
GenServer.stop(pid, reason, timeout)!
end!
def terminate(reason, state) do!
CALLBACK
# Perform cleanup here!
# !
end!
:normal!
REASON*
:shutdown!
{:shutdown, term}!
term!
The Little Elixir & OTP Guidebook
gets you started programming applications with Elixir and OTP. You begin
with a quick overview of the Elixir language syntax, along with just enough
functional programming to use it eectively. Then, you'll dive straight into OTP
and learn how it helps you build scalable, fault-tolerant and distributed
applications through several fun examples. Come rediscover the joy of
programming with Elixir and remember how it feels like to be a beginner
again. Psst! Use tanweihao39 for 39% o!
Copyright Benjamin Tan Wei Hao. Free to use without modication for non-commercial applications.