GenServer Callbacks

GenServer is an OTP protocol. OTP works by assuming that your module defines a number of callback functions (six, in the case of a GenServer). If you were writing a GenServer in Erlang, your code would have to contain implementations of all six.

When you add the line 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 behaviour. Our examples so far have used the two callbacks handle_call and handle_cast. Here’s a full list:

init(start_arguments)

Called by GenServer when starting a new server. The parameter is the second argument passed to start_link. Should return {:ok, state} on success, or {:stop, ...

Get Programming Elixir 1.3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.