Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Agents

agents.livemd

Agents

A simpler Genserver

An Agent is a way of getting many of the benefits of a Genserver to store state with a simple interface.

You can basically either read the current state, or update it (there is a command to do both at the same time)

{:ok, agent} = Agent.start_link(fn -> 4 end)
Agent.update(agent, fn state -> state + 1 end)
Agent.get(agent, fn state -> state end)
# A little gotcha - this function requires a tuple - the returned value and the new state
val = Agent.get_and_update(agent, fn state -> {state + 1, state + 1} end)
Agent.stop(agent)