Simple Agent Sample

Elixir does not have global variables.
This can make certain operations difficult.

This is where an Agent helps:

{:ok, pid} = Agent.start(fn -> 42 end)
pid |> Agent.get( & &1)
pid |> Agent.update(&(&1 + 1))
pid |> Agent.get( & &1)

This wtaps some state in a Process.

Since it is only updated via messages some concurrency issues are removed,
Privacy is achieved by keeping the pid hidden.

Note that the simple update has a 5 second timeout. The update will fail if it takes too long.




Leave a comment