GenServer
| start_link | |
| Sync call | |
| Async cast | |
| State in a loop |
start_link
A GenServer is a process that holds state and answers requests through callbacks. The use line wires the behaviour while init sets the starting state from its argument. The start_link call launches the server tied to the caller and returns an ok tuple with the pid.
defmodule Counter do
use GenServer
def init(start) do
{:ok, start}
end
end
{:ok, pid} = GenServer.start_link(Counter, 0)
Sync call
The call function sends a request and waits until the server replies, which makes it right for reads. The handle_call callback receives the message, the caller reference, and the current state, then returns a reply tuple carrying the answer and the state. Here the server answers with its count and keeps it unchanged.
def handle_call(:get, _from, count) do
{:reply, count, count}
end
GenServer.call(pid, :get)
0
Async cast
The cast function drops a message and returns at once without waiting, which suits updates and notifications. The handle_cast callback receives the message and the state, then returns a noreply tuple with the new state. Here the server adds five and stores the result.
def handle_cast({:add, n}, count) do
{:noreply, count + n}
end
GenServer.cast(pid, {:add, 5})
:ok
State in a loop
State flows from callback to callback: init builds it, handle_cast transforms it, and handle_call reads it. Calls and casts from one client reach the mailbox in order, so a cast followed by a call observes the update. Starting from ten, adding five, then reading back yields fifteen.
{:ok, pid} = GenServer.start_link(Counter, 10)
GenServer.cast(pid, {:add, 5})
GenServer.call(pid, :get)
15
Next: Supervisors
Article author: Arthur Isaev