...

/

Keeping State With Elixir Agents

Keeping State With Elixir Agents

Learn about the use of Elixir Agents and how to use them in an API.

The Elixir Agent module provides a simple way to store and retrieve the state in our application. Let’s see how easy it is to manage the state with an Agent process, by executing the following commands in sequence in the iex shell:

iex> {:ok, buffer} = Agent.start_link fn -> [] end 
# Output: {:ok, #PID<0.130.0>}
iex> Agent.get(buffer, fn state -> state end) 
# Output: []
iex> Agent.update(buffer, &["<h2>Hello</h2>" | &1]) 
# Output: :ok
iex> Agent.get(buffer, &(&1)) 
# Output: ["<h2>Hello</h2>"]
iex> for i <- 1..3, do: Agent.update(buffer, &["<td><#{i}</td>" | &1]) 
# Output: [:ok, :ok, :ok]
iex> Agent.get(buffer, &(&1))
# Output: ["<td><3</td>", "<td><2</td>", "<td><1</td>", "<h2>Hello</h2>"]
Terminal 1
Terminal
Loading...

The use of Agent module:

The Agent module has a small API, which focuses on providing quick access to the state. In the ...

Access this course and 1400+ top-rated courses and projects.