Elixir foundationSort Order

Elixir: GenServer Handle Cast - [015]

Handle casts are different from calls in that they don't return anything. Users can use cast when making an operation without expecting any return value.

Handle Cast

Let's take a look at an example

def swap_url(pid, new_url) do  GenServer.cast(pid, {:swap_url, new_url})enddef handle_cast({:swap_url, new_url}, _state) do  {:noreply, %{url: new_url}}end

This will update the state of the GenServer without returning any value. We can call the swap_url function which will invoke the handle_cast that updates the state of the GenServer. The updated GenServer looks like this.

defmodule Botiful.Render.Engine do  # Public API (Client)    def start_link(url) do    GenServer.start_link(__MODULE__, url)  end    def url(pid) do    GenServer.call(pid, :url)  end    def swap_url(pid, new_url) do    GenServer.cast(pid, {:swap_url, new_url})  end     # Server Callbacks     def init(url) do    {:ok, %{url: url}}  end     def handle_call(:url, _from, state) do    {:reply, state.url, state}  end    def handle_cast({:swap_url, new_url}, _state) do    {:noreply, %{url: new_url}}  endend

In the next episode we will start writing the code for the rendering engine!