Today I Learned

hashrocket A Hashrocket project

An Agent reference can be pid or name.

Each function of the Agent module takes an agent as the first argument:

get(agent, fun, timeout \\ 5000)

but this can be a couple of different things. The documentation defines the agent type as:

agent :: pid | {atom, node} | name

#The agent reference

name ::
  atom |
  {:global, term} |
  {:via, module, term}

#The agent name

So really five different types of values are valid. The pid is a value returned from calling start_link.

> {:ok, agent_pid} = Agent.start_link(fn -> [:thing] end)
> Agent.get(agent_pid, fn (state) -> hd(state) end)
:thing

The agent can be referenced by a name atom also. In the documentation example that name atom is the __MODULE__ for the module that wraps access to the agent. The name for the agent is declared by passing a name option into the start_link function call.

> Agent.start_link(fn -> [:thing] end, name: __MODULE__)
> Agent.get(__MODULE__, fn (state) -> hd(state) end)
:thing

I'm note sure about the {:global, term} and {:via, module, term} values that seem to be valid. I would love to see examples for those.

See More #elixir TILs
Looking for help? At Hashrocket, we 💜 Elixir! From our many Elixir client projects, to sponsoring the Chicago Elixir Meetup, to the source code for this application, we are invested in this community. Contact us today to talk about your Elixir project.