O'Reilly logo

Elixir Cookbook by Paulo A Pereira

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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:

  1. Open your code editor and create a file named phone_book.ex.
  2. 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) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required