LoginSignup
1
0

More than 5 years have passed since last update.

[Elixir] ある特定の名前を持つAgentが存在するか判定する

Posted at

↓のような感じである名前を持ったAgentが存在しているか判定し、
存在していかったらAgentを開始させてあげたい

defmodule MyAgent do

  def get(agent_name) do
    unless Agent.exists?(agent_name) do #Agent.exists? はない
      Agent.start_link(fn -> 1 end, name: agent_name)
    end
    Agent.get(agent_name, fn state -> state end)
  end
end

Elixirではプロセスに名前を登録することができる。
ある名前をもったプロセスが存在するかどうかは以下の関数で判定できそう

Process.whereis/1

iex(1)> Process.whereis(:hoge)
nil
iex(2)> Agent.start_link(fn -> 1 end, name: :hoge)
{:ok, #PID<0.83.0>}
iex(3)> Process.whereis(:hoge)
#PID<0.83.0>

なので冒頭のコードは以下のように書けばいけそう

defmodule MyAgent do

  def get(agent_name) do
    unless Process.whereis(agent_name) do
      Agent.start_link(fn -> 1 end, name: agent_name)
    end
    Agent.get(agent_name, fn state -> state end)
  end
end
1
0
7

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0