GenServer at your service

As we briefly hinted at before, we can leverage the GenServer behaviour to implement a process that will provide some kind of service through a well-defined public interface. To do so, one only has to use GenServer in its module and implement the necessary callbacks:

iex> defmodule Calculator do...>   use GenServer...>...>   def handle_call({:mult5, number}, _from, state) do...>     {:reply, number*5, state}...>   end...> end{:module, Calculator, <<70, 79, 82, 49, 0, 0, 12, 224, 66, 69, 65, 77, 65, 116,  85, 56, 0, 0, 1, 138,   0, 0, 0, 42, 17, 69, 108, 105, 120, 105, 114, 46, 67,  97, 108, 99, 117, 108,   97, 116, 111, 114, 8, 95, 95, 105, 110, ...>>,    {:handle_call, 3}}iex> {:ok, calc} = GenServer.start_link(Calculator, []) ...

Get Mastering Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.