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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.