Search code examples
elixiragents

Unable to use the value returned by Agent in a loop in elixir


So I have elixir program which runs in a loop and perform certain operations. I have declared an Agent to create a single zookeeper connection instance and then use the same in the loop. Following is my code:-

mix.exs

def application do
[ 
  applications: [:logger, :zookeeper],
  mod: {ServiceMonitor, []}
]

end    

defp deps do
[
  {:zookeeper, github: "vishnevskiy/zookeeper-elixir"}
]
end

service_monitor.ex

defmodule ServiceMonitor do
  def start(_type, _args) do
    {:ok, zk_agent} = Agent.start_link(fn -> ServiceMonitor.Registry.get_zk end)
    ServiceMonitor.Registry.start_process(zk_agent)
   end
end 

service_monitor/registry.ex

defmodule ServiceMonitor.Registry do
  alias Zookeeper.Client, as: ZK
  def start_process(zk) do

    pid = spawn_link(fn ->
        {:ok, data} = ZK.get_children(zk, "/test")
        IO.inspect(data)
    end)

    start_process(zk)

  end

  def get_zk do
    {:ok, zk} = ZK.start("localhost:2181")
    zk
  end
end

Now if I print the pid of the zk, i always get the same which means that the same instance of zk is returned always. But i am getting the following error:-

12:44:39.647 [error] GenServer #PID<0.165.0> terminating
** (stop) bad call: #Operation performed by zk
(elixir) lib/gen_server.ex:420: Agent.Server."handle_call (overridable 1)"/3
(stdlib) gen_server.erl:629: :gen_server.try_handle_call/4
(stdlib) gen_server.erl:661: :gen_server.handle_msg/5
(stdlib) proc_lib.erl:240: :proc_lib.init_p_do_apply/3
Last message: #
State: {:ok, #PID<0.166.0>} 

Also, if I always initialize the zk in loop instead of referencing from the agent, my code is working fine.

PS:- To reproduce it you need to have a zookeeper setup


Solution

  • It seems that I was wrongly running the loop for the spawned process. Dogbert's solution on how to get the value returned by the agent in the loop actually worked. Now, I am running the loop on the spawned process as follows:-

    def start_process(zk_agent) do
        spawn(ServiceMonitor.Registry, :start,[zk_agent])
        :timer.sleep(@sleep_time)
        start_process(zk_agent)
    end
    
    def start_process(zk_agent) do
        zk = Agent.get(zk_agent, &(&1))
        #Other logics
    end