dsnipe

dsnipe

How to get keys of registered children (via Register)

Hello.
I want to use Registry module to register dynamically created children processes.
So I added registry into my supervisor tree:

def init([]) do
    children = [
      supervisor(Registry, [:unique, :my_registry]),
      supervisor(MyManager, []),
      ...
    ]
    opts = [strategy: :one_for_one, name: MySupervisor]
    supervise(children, opts)
  end

Registration of children happens like this:

  def start_link(%{id: id}) do
    GenServer.start_link(__MODULE__, [], name: {:via, Registry, {:my_registry, id}})
  end

So, my questions is – how to get all keys (children pids) in my Registry.
I tried to use Registry.keys\2, but without success.

def get_registry_pid do
    Supervisor.which_children(MySupervisor)
    |> Enum.filter(fn {id, _, _, _} -> id == Registry end)
    |> List.first
    |> elem(1) # get a Regisry pid from a tuple {id, pid, type, modules}
end
Registry.keys(:my_registry, get_registry_pid()) # returns []
# but 
Registry.lookup(:my_registry, id) # returns PID as expected

Thanks in advance for any help!

Marked As Solved

dsnipe

dsnipe

Thank for the answer @arkgil!
In the end I figured out how Registry works. It links a key/value to a process which used to register it. So in my case each id is linked to a process (on starting procedure using :via) and when this process dies, the key automatically deletes from Registry (because linked to it).
Answer is – it’s impossible to iterate through these ids in Registry, but it’s possible to use Supervisor.which_children and get all children pids instead :slight_smile:
I also use Registry to store an additional data for processes (using processes itself to register data), and it automatically cleans when a process killed.

Also Liked

darraghenright

darraghenright

I have to say, I was initially a bit perplexed by Registry.keys/2. I think I misunderstood its functionality based on some incorrect, preconceived notions.

I discovered this thread when trying to figure out my use case, so I figured I’d add a post in case it’s useful to someone in future.

I just wanted to get a list of all registered keys in a registry and assumed (without reading the docs to be fair) that Registry.keys/2 would do that, in much the same way that Registry.count/1 returns a count of all items in a registry.

I read through the docs a bit and realised that Registry.select/2 does this; i.e:

# get a list of keys
Registry.select(MyRegistry, [{{:"$1", :_, :_}, [], [:"$1"]}])

# get a list of two-element key/pid tuples
Registry.select(MyRegistry, [{{:"$1", :"$2", :_}, [], [{{:"$1", :"$2"}}]}])
adammokan

adammokan

Looks like you have it figured out, but I have a sample project here - GitHub - amokan/registry_sample: Example application using the new Registry module in Elixir 1.4.0 · GitHub

In particular, you can look at how I used the Supervisor.which_children to get the registry keys here - registry_sample/lib/registry_sample/account_supervisor.ex at master · amokan/registry_sample · GitHub

arkgil

arkgil

Second argument passed to Registry.keys/2 is a pid of a process which put an entry into registry (i.e. the one which called Registry.register/3 which is done behind the scenes when using :via option). I think that in your case it is a pid of MySupervisor because this is the process which called start_link/1 of your workers.

Try it with supervisor’s pid and let us know if that worked! :slight_smile:

Where Next?

Popular in Questions Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> somethi...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New

Other popular topics Top

hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43806 214
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement