Elixir foundationSort Order

Elixir: Agent Basics - [016]

We'll be covering Agent in this episode. Agents are great for state management in elixir.

Starting an Agent

We can use start_link to start an agent.

{:ok, pid} = Agent.start_link(fn -> %{} end)

Getting the State

We can retrieve the state from the agent by using get

Agent.get(pid, fn state -> state end)

Updating the State

We can update the state by using update

Agent.update(pid, fn state -> Map.merge(state, %{name: "Zack"}) end)

Get and Update

We can also get and update in a single call

Agent.get_and_update(pid, fn state -> {state, Map.merge(state, %{age: 34}) end)

This will return the existing state so we will get:

%{name: "Zack"}

But the actual state will now have changed. If we get the state again we will get:

%{name: "Zack", age: 34}