Registry: dispatch vs lookup

I was checkin the documentation about Registry.dispatch/3 and Registry.lookup/2. The only one difference between both (for me) is dispatch perform the execution of a closure with the data returned by the registry so:

Registry.dispatch Data, :key, fn entries ->
  Enum.each(entries, &(IO.inspect(&1)))

It should be the same as:

Registry.lookup Data, :key 
|> Enum.each(&(IO.inspect(&1))

And even both closures are running in the caller process so, why Registry.dispatch/3 is better or recommended?

1 Like

I’m not using registry, but let me ask a question, how do the both methods behave when there is no value associated to that key?

It’s behaving in the same way:

iex(25)> Registry.start_link keys: :duplicate, name: Game
{:ok, #PID<0.212.0>}
iex(26)> Registry.dispatch Juego, :lake, fn entries -&gt; for {_, {nombre, edad}} &lt;- entries do
...(26)>     IO.puts "player =>\n\tnombre -> #{nombre}\n\tedad -> #{edad}"
...(26)>   end
...(26)> end
iex(27)> Registry.lookup(Juego, :lake) |> Enum.each(fn {_, {nombre, edad}} ->
...(27)> IO.puts "player =>\n\tnombre -> #{nombre}\n\tedad -> #{edad}"
...(27)> end)

Dispatch passes into your closure the pid of the process that put the entry in.

This is of course not the only way to achieve calling back to the original registrant, it’s a convenience for it.

1 Like