Skip to content

Instantly share code, notes, and snippets.

@adkron
Created September 13, 2017 21:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adkron/645a5bbceb1adaf585756ca3b9515313 to your computer and use it in GitHub Desktop.
Save adkron/645a5bbceb1adaf585756ca3b9515313 to your computer and use it in GitHub Desktop.
defmodule DeviceHandler.EventBus do
def new(opts) do
Registry.start_link(opts)
end
def child_spec([]) do
child_spec name: __MODULE__,
keys: :duplicate
end
def child_spec(opts) do
%{
id: __MODULE__,
start: {__MODULE__, :new, [opts]},
type: :supervisor,
}
end
def subscribe(registry, message, serial \\ :all) do
Registry.register(registry, message, serial)
end
def update(hub), do: update(__MODULE__, hub)
def update(registry, hub) do
serial = hub.serial
Registry.dispatch(registry, :update, fn(subscribers) ->
for {pid, intrest} <- subscribers, interested?(intrest, serial), do: brodcast({:update, hub}, pid)
end)
end
def remove(hub), do: remove(__MODULE__, hub)
def remove(registry, serial) do
Registry.dispatch(registry, :remove, fn(subscribers) ->
for {pid, intrest} <- subscribers, interested?(intrest, serial), do: brodcast({:remove, serial}, pid)
end)
end
defp interested?(:all, _), do: true
defp interested?(intrest, serial), do: intrest == serial
defp brodcast(event, pid), do: send(pid, {:event, event})
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment