GenServer callbacks in-depth

The best way to learn about callbacks is to see them in action. We’ll add some functionality to the SendServer module and introduce the most common GenServer callbacks along the way.

We can implement a callback by declaring it in the SendServer module like any other function. By doing this, we are replacing the default function that GenServer provides. This is sometimes called overriding the default implementation. When we implement a callback, there are two things we need to know:

  • What arguments does the callback function take?

  • What return values are supported?

Callbacks covered

We are going to cover the following callback functions for the GenServer behaviour:

  • handle_call/3

  • handle_cast/2

  • handle_continue/2

  • handle_info/2

  • init/1

  • terminate/2

Learning about these callbacks enables us to take full advantage of our GenServer process. We’ll skip two callbacks, code_change/2 and format_status/2. We’ll also focus on the most frequently used return values, leaving some behind. All callbacks and return values are well documented on Elixir’s HexDocs page, so feel free to go online and explore GenServer further.

Explore callbacks for behaviours

The easiest way to find out what callbacks are available for a specific behaviour is to check the documentation for the module on HexDocs:

  • We use the left sidebar to navigate to “Modules” and find the module name in the list of categories.

  • “GenServer” can be found under “Processes & Applications.” When we click on the module name, it expands and shows us a few sub-items:

    • “Top”

    • “Sections”

    • “Summary”

    • “Types”

    • “Functions”

    • “Callbacks”

When we click on “Callbacks”, we see the links to the functions available for us to implement.

Get hands-on with 1200+ tech skills courses.