Building a Concurrent System


Elixir in Action: Chapter 7

The GenServer handle_call function returns state to the GenServer, which messages it back to the caller. You can also spawn a worker process, return state to the GenServer instructing it not to message back to the caller, then send a message directly from the spawned worker function.

Example provided in the chapter:

def handle_call({:get, key}, caller, state) do
  spawn(fn ->
    data = case File.read(file_name(key)) do
      {:ok, contents} -> :erlang.binary_to_term(contents)
      _ -> nil
    end

    GenServer.reply(caller, data)
  end)

  {:noreply, state}
end

Notable Notes and Quotes

  • Use the handle_continue function to implement a slow GenServer initialization process.
  • Downside: you won’t know if it succeeded.
  • Tests are broken as they do not clear the ./persist/ directory between runs.

My Github repository. Book samples Github code samples.

Quotes are excerpts From Elixir in Action, Third Edition, Sasa Juric. All notes and comments are my own opinion. Follow me at @rgacote@genserver.social