Skip to content
This repository was archived by the owner on Apr 11, 2019. It is now read-only.

Commit 558b01d

Browse files
author
José Valim
committed
Add an example of safe dispatch
1 parent a0f1217 commit 558b01d

File tree

1 file changed

+25
-3
lines changed

1 file changed

+25
-3
lines changed

lib/registry.ex

+25-3
Original file line numberDiff line numberDiff line change
@@ -65,9 +65,31 @@ defmodule Registry do
6565
value registered is a `{module, function}` tuple, allowing each entry to be
6666
invoked by the calling process.
6767
68-
Keep in mind dispatching happens in the process that calls `dispatch/3`,
69-
registered processes are not involved in dispatching unless they are
70-
explicitly sent messages to. That's the example we will see next.
68+
Keep in mind dispatching happens in the process that calls `dispatch/3`.
69+
The registered processes are not involved in dispatching unless such is
70+
done explicitly. In the example, if there is a failure when dispatching,
71+
due to a bad registration, dispatching will always fail. Let's fix that
72+
by wrapping and reporting errors:
73+
74+
iex> require Logger
75+
iex> {:ok, _} = Registry.start_link(:duplicate, Registry.DispatcherTest)
76+
iex> {:ok, _} = Registry.register(Registry.DispatcherTest, "hello", {IO, :inspect})
77+
iex> Registry.dispatch(Registry.DispatcherTest, "hello", fn entries ->
78+
...> for {pid, {module, function}} <- entries do
79+
...> try do
80+
...> apply(module, function, [pid])
81+
...> catch
82+
...> kind, reason ->
83+
...> formatted = Exception.format(kind, reason, System.stacktrace)
84+
...> Logger.error "Registry.dispatch/3 failed with #{formatted}"
85+
...> end
86+
...> end
87+
...> end)
88+
# Prints #PID<...>
89+
:ok
90+
91+
You could also replace the whole `apply` system by explicitly sending
92+
messages. That's the example we will see next.
7193
7294
## Using as a PubSub
7395

0 commit comments

Comments
 (0)