Using agents as an abstraction around states
The Agent
module provides a basic server implementation and is a convenient way to spawn a process that needs to maintain a state. Agents in Elixir provide an intuitive API to update and retrieve the state.
In this recipe, we will create a module, phone_book.ex
, where we will be able to store and retrieve data.
How to do it…
To create our phone book using an agent to maintain states, follow these steps:
Open your code editor and create a file named
phone_book.ex
.Add the following code to the file you created:
defmodule PhoneBook do @name __MODULE__ def start_link do Agent.start_link(fn -> %{} end, name: @name) end def insert(user, number) do Agent.update(@name, &Map.put(&1, user, number)) end def get(user) do Agent.get(@name, &Map.get(&1, user)) end end
Start IEx and load the module:
> iex phone_book.ex
Start the process that will hold our phone book data:
iex(1)> PhoneBook.start_link {:ok, #PID...