typestar

Agents in Elixir

A note jar kept by an Agent: state lives in a process, not in a variable.

# An Agent is a small process whose whole job is holding state.
{:ok, jar} = Agent.start_link(fn -> [] end)

Agent.update(jar, fn notes -> ["sharpen the scythe" | notes] end)
Agent.update(jar, fn notes -> ["patch the beehive roof" | notes] end)

IO.puts("notes saved: #{Agent.get(jar, fn notes -> length(notes) end)}")

Agent.get(jar, fn notes -> notes end)
|> Enum.each(fn note -> IO.puts("- " <> note) end)

Agent.stop(jar)

How it works

  1. Agent.start_link boots the process with an empty list as its state.
  2. Each Agent.update prepends a note by running a function on the current state.
  3. Agent.get reads through a function too, and Agent.stop retires the jar.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
425
Tokens
116
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 99 seconds.

Type this snippet

Step 3 of 3 in Processes, step 24 of 27 in Language basics.

← Previous Next →