Responding with :stop allows call of `terminate`
A GenServer in Elixir has two lifecycle methods, init
and terminate
. init
is called when the GenServer is started with GenServer.start_link
.
What I learned today is that there is a terminate
method in case there's any resources that need to be cleaned up when the GenServer is shut down. The terminate
method is called when the :stop message is returned from either handle_cast
or handle_call
:
defmodule Cache do
use GenServer
#... a lot of other code
def handle_cast({:something, 1}, state) do
IO.puts "This executes first"
{:stop, "This is my reason for stopping", state}
end
def terminate(reason, state)
IO.puts "Then this executes"
end
end
Tweet