Skip to content

Instantly share code, notes, and snippets.

@adkron
Created Sep 13, 2017
Embed
What would you like to do?
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