Mahmud Adam
Mahmud Adam

Reputation: 3579

More than one Agent in a single module

Is it okay to have more than one Agent in a module? For instance, I am creating a game and I need a wrapper for the state of the game as well as a wrapper for the state of the users. An example:

defmodule TicTacToe do

  def start_game do
    Agent.start_link(..., name: Moves)
    Agent.start_link(..., name: Users)
  end

end

The examples in the docs show a single Agent.start_link which makes me think there shouldn't be more than one Agent.

Upvotes: 0

Views: 124

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

While it is absolutely legit to have as many Agents as you want (they are still erlang’s gen_servers under the hood,) there is no need in two agents in this particular case.

The rule of thumb is “do not produce superfluous servers.“

One map with keys :moves and :users would perfectly suffice here:

@doc """
Starts a new single agent for both moves and users.
"""
def start_link do
  Agent.start_link(fn -> %{moves: %{}, users: %{}} end)
end

@doc """
Gets a move by `key`.
"""
def get_move(key) do
  Agent.get(&get_in(&1, [:moves, key]))
end

Here we use the deep map digging with Kernel.get_in/2. That is preferrable way because as soon as you are writing the robust application, you should take care about data consistence over crashes, and it’s easier to just take care about one Agent, rather than keep many of them consistent.

Upvotes: 3

Related Questions