The model - what is an agent?

Agents are another common implementation in the Elixir concurrency world, especially around the context of state management. agents are pretty much designed for that sole purpose: they exist to be simple wrappers around state! They're incredibly simple to work with. Let's open an IEx window (if we don't already have one open) and begin implementing a simple agent:

iex(1)> {:ok, agent} = Agent.start_link(fn -> %{} end){:ok, #PID<0.174.0>}

We start off by initializing our agent with Agent.start_link/1. This function takes in a single argument, which is the function that returns the agent's initial state. In the preceding case we're starting off with a completely blank map:

iex(2)> Agent.update(agent, fn state -> ...

Get Phoenix Web Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.