jonnifyelixir
F3 / F3.08 / genserver

F3.08 · part 1 of 3

The GenServer behaviour

A GenServer is a behaviour (F3.06) that abstracts the receive loop (F3.07). You implement callbacks — init/1 sets the starting state, handle_call/3 answers synchronous requests, handle_cast/2 handles asynchronous ones — and the framework runs the loop, the mailbox, and the replies. The state you return threads into the next callback.

The portal's hand-written tally becomes a GenServer. Each callback returns a tagged tuple that tells the framework what to reply and what the next state is. Select a callback and read its return and its effect on the state.

The callbacks and their returns

Each callback receives the current state and returns a tuple. init/1 returns {:ok, state}; handle_call/3 returns {:reply, value, state}; handle_cast/2 returns {:noreply, state}. Select one and see what it returns and how the state moves.

The callback · select one

GENSERVER CALLBACKS init(arg) selected handle_call(request, from, state) selected handle_cast(request, state) selected RETURNS {:ok, 0} STATE starts at 0

      

The return tuple is the whole contract with the framework: its tag decides whether the caller gets a reply, and its last element becomes the state handed to the next message.

The whole module

use GenServer brings in the loop and default callbacks; you add the ones you care about, each marked @impl true. A thin client API wraps the raw GenServer calls so callers never touch the PID protocol directly.

defmodule Portal.Tally do
  use GenServer

  # client API
  def start_link(n), do: GenServer.start_link(__MODULE__, n)

  # callbacks
  @impl true
  def init(n), do: {:ok, n}

  @impl true
  def handle_call(:get, _from, count), do: {:reply, count, count}

  @impl true
  def handle_cast(:inc, count), do: {:noreply, count + 1}
end

F3.07 · the hand-written loop

You wrote receive, the reply send, and the recursive loop(state) by hand.

In Elixir

use GenServer runs the loop; you fill in init, handle_call, and handle_cast.

Next: synchronous call, asynchronous cast — the two ways a client reaches these callbacks.

References

Primary sources for this lesson, and where it connects in the course.

Sources

Related in this course