Elixir foundationSort Order

Elixir: GenServer Handle Call - [014]

We will need to be able to retrieve data from our GenServer. In this post we will explore how handle_call works.

Handle Call

def url(pid) do  GenServer.call(pid, :url)end def handle_call(:url, _from, state) do  {:reply, state.url, state}end

When we call the url function passing in the pid it will invoke the handle_call callback which we can then use to return the url from the state. The updated GenServer looks like the following.

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     # Server Callbacks     def init(url) do    {:ok, %{url: url}}  end     def handle_call(:url, _from, state) do    {:reply, state.url, state}  endend