Created
September 13, 2017 21:46
-
-
Save adkron/645a5bbceb1adaf585756ca3b9515313 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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