Skip to content
Elixir

GenServer

Построение процессов-серверов с состоянием через behaviour GenServer.

#genserver#otp#state

Code

elixir
defmodule Counter do
  use GenServer

  # Client API
  def start_link(initial \ 0), do: GenServer.start_link(__MODULE__, initial, name: __MODULE__)
  def increment, do: GenServer.cast(__MODULE__, :inc)
  def value, do: GenServer.call(__MODULE__, :value)

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

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

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

# Usage
{:ok, _} = Counter.start_link(0)
Counter.increment()
Counter.increment()
IO.puts(Counter.value())  # 2