Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Elixir Cookbook

You're reading from   Elixir Cookbook Unleash the full power of programming in Elixir with over 60 incredibly effective recipes

Arrow left icon
Product type Paperback
Published in Feb 2015
Publisher Packt
ISBN-13 9781784397517
Length 236 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Paulo Pereira Paulo Pereira
Author Profile Icon Paulo Pereira
Paulo Pereira
Arrow right icon
View More author details
Toc

Table of Contents (11) Chapters Close

Preface 1. Command Line 2. Data Types and Structures FREE CHAPTER 3. Strings and Binaries 4. Modules and Functions 5. Processes and Nodes 6. OTP – Open Telecom Platform 7. Cowboy and Phoenix 8. Interactions A. Installation and Further Reading Index

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) do
        Agent.get(@name, &Map.get(&1, user))
      end
    
    end
  3. Start IEx and load the module:

    > iex phone_book.ex
    
  4. Start the process that will hold our phone book data:

    iex(1)> PhoneBook.start_link
    {:ok, #PID...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime