Genserver Callbacks: handle_cast

Learn how the GenServer uses handle_cast to interact with processes.

The handle_cast callback function

Now, let’s implement sending emails using handle_cast/2. The arguments given to handle_cast/2 are just a term for the message and the state. We pattern match on the message {:send, email}:

def handle_cast({:send, email}, state) do 
    # to do...
end

Return values

Most of the times we will return one of the following tuples:

  • {:noreply, new_state}

  • {:noreply, new_state, {:continue, term}}

  • {:stop, reason, new_state}

To refresh our memory, this is how the Sender.send_email/1 function works:

def send_email(email) do
   Process.sleep(3000)
   IO.puts("Email to #{email} sent")
   {:ok, "email_sent"}
end

Let’s call the send_email/1 function from our handle_cast/2 callback and update the process state when this happens:

Get hands-on with 1200+ tech skills courses.