Elixir
GenServer
Build stateful server processes with GenServer behaviour.
By EZ4Code Team
genserverotpstate
Code
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()) # 2Explanation
GenServer is the OTP behaviour for stateful server processes. Client API (synchronous call / asynchronous cast) sends messages to a server loop that handles init/handle_call/handle_cast. The state is threaded through each callback. This pattern abstracts the receive loop, provides supervision, and integrates with the broader OTP tree.
More Elixir Snippets
Pattern Matching
Pattern matching is core to Elixir — used everywhere.
Pipe Operator
Chain function calls with the |> pipe operator.
Processes and Messages
Spawn lightweight processes and send messages.
Supervisors and OTP
Build fault-tolerant supervision trees.
Protocols and Enums
Polymorphism via protocols and the Enum module.
Enum and Stream Operations
Functional collection operations in Elixir.