Agents

An agent is a background process that maintains state. This state can be accessed at different places within a process or node, or across multiple nodes.

The initial state is set by a function we pass in when we start the agent.

We can interrogate the state using Agent.get, passing it the agent descriptor and a function. The agent runs the function on its current state and returns the result.

We can also use Agent.update to change the state held by an agent. As with the get operator, we pass in a function. Unlike with get, the function’s result becomes the new state.

Here’s a bare-bones example. We start an agent whose state is the integer 0. We then use the identity function, &(&1), to return that state. Calling Agent.update with ...

Get Programming Elixir 1.2 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.