GenServer Callbacks
Learn about different GenServer callbacks in Elixir.
We'll cover the following...
- GenServer
- init(start_arguments)
- handle_call(request, from, state)
- handle_cast(request, state)
- handle_info(info, state)
- terminate(reason, state)
- code_change(from_version, state, extra)
- format_status(reason, [pdict, state])
- { :noreply, new_state [ , :hibernate | timeout ] }
- { :stop, reason, new_state }
- { :reply, response, new_state [ , :hibernate | timeout ] }
- { :stop, reason, reply, new_state }
GenServer
GenServer is an OTP protocol. OTP works by assuming that our module defines a number of callback functions. There are six in the case of a GenServer. If we were writing a GenServer in Erlang, our code would have to contain implementations of all six functions.
When we add the statement use GenServer
to a module, Elixir creates default implementations of these six callback functions. All we have to do is override the ones where we add our own application-specific behavior. Our examples so far have used the three callbacks init
, handle_call
, and handle_cast
. Here, we’ll look at the full list.
init(start_arguments)
GenServer calls init(start_arguments)
when starting a new server. The parameter is the second argument passed to start_link
. It should return {:ok, state}
on success, or {:stop, reason}
if the server couldn’t be started.
We can specify an ...