GenServer.Behaviour

This module is a convenience for defining GenServer callbacks in Elixir.

A server is responsible for reacting to messages received from a client. A GenServer is an OTP behaviour that encapsulates common server functionalities.

Example

Below is an example of a GenServer that pushes and pops items onto a stack:

defmodule MyServer do
  use GenServer.Behaviour

  # Callbacks

  def handle_call(:pop, _from, [h|t]) do
    { :reply, h, t }
  end

  def handle_call(request, from, config) do
    # Call the default implementation from GenServer.Behaviour
    super(request, from, config)
  end

  def handle_cast({ :push, item }, config) do
    { :noreply, [item|config] }
  end

  def handle_cast(request, config) do
    super(request, config)
  end
end

{ :ok, pid } = :gen_server.start_link(MyServer, [:hello], [])

:gen_server.call(pid, :pop)
#=> :hello

:gen_server.cast(pid, { :push, :world })
#=> :ok

:gen_server.call(pid, :pop)
#=> :world

Notice we never call the server callbacks directly, they are called by OTP whenever we interact with the server. cast messages are asynchronous while call ones are synchronous. For a GenServer, there are 8 different values a callback such as handle_call or handle_cast can return:

{ :reply, reply, new_state }
{ :reply, reply, new_state, timeout }
{ :reply, reply, new_state, :hibernate }
{ :noreply, new_state }
{ :noreply, new_state, timeout }
{ :noreply, new_state, :hibernate }
{ :stop, reason, new_state }
{ :stop, reason, reply, new_state }

There are 6 callbacks required to be implemented in a GenServer. The GenServer.Behaviour module defines all of them automatically, but allows us to customize the ones we need. The required callbacks are:

Starting and sending messages to the GenServer is done via Erlang's :gen_server module. For more information, please refer to the following:

Source