GenServer Callbacks: init
Explore how to implement and override GenServer callbacks in Elixir, focusing on the init function to initialize process state. Understand the significance of various return values and how to manage process startup, configuration, and post-initialization tasks effectively.
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 ...