Elixir Medium · Lesson 1 · On the house

GenServer basics

use GenServer, start_link, call vs cast. Lesson 1 is free — on the house.

Lessons · Elixir Medium · Lesson 1 of 10 · On the house

GenServer basics

use GenServer, start_link, call vs cast.

Illustration for Elixir
Lesson 1 is on the house.

A GenServer is a process with a standard callback interface for state and messages. use GenServer pulls in the behaviour and default callbacks. You implement init/1 and the handlers you need.

GenServer.start_link(Module, init_arg, opts \\ []) starts a linked process. It calls Module.init(init_arg), which should return {:ok, state}. The return of start_link is {:ok, pid} (or {:error, reason}).

GenServer.call(server, request) is synchronous: the caller blocks until handle_call replies. GenServer.cast(server, request) is asynchronous: fire-and-forget; no reply is waited for.

Put the public API on the module (start_link, get, inc) and have those functions call GenServer.call/cast with the server PID or name. Keep GenServer details behind that API.

Misses: using cast when you need a return value, forgetting use GenServer, or returning a bare state from init/1 instead of {:ok, state}.

genserver-basics

defmodule CounterGS do
  use GenServer

  def start_link(n \\ 0) do
    GenServer.start_link(__MODULE__, n)
  end

  def get(pid), do: GenServer.call(pid, :get)
  def inc(pid), do: GenServer.cast(pid, :inc)

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

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

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

{:ok, pid} = CounterGS.start_link(0)
CounterGS.inc(pid)
IO.inspect(CounterGS.get(pid))
Match this when you type.

Quiz

What does use GenServer provide?

Quiz

What must init/1 return for a successful start?

Quiz

How does GenServer.call differ from cast?

Quiz

Where should public API functions live?

Check

Match the still for: GenServer basics.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.