Skip to content

Instantly share code, notes, and snippets.

@TattdCodeMonkey
Last active February 19, 2016 11:52
Show Gist options
  • Save TattdCodeMonkey/9270ceec00325bfda907 to your computer and use it in GitHub Desktop.
Save TattdCodeMonkey/9270ceec00325bfda907 to your computer and use it in GitHub Desktop.
Trivial mostly representative example of GenEvent usage for blog post
# supervisor.ex
defmodule EventSup do
use Supervisor
def start_link, do: Supervisor.start_link(__MODULE__, [], [])
def init(_) do
supervise(
[
worker(GenEvent, [[name: :event_manager]], [id: :event_manager]),
worker(EventMonitor, [:event_manager])
],
[strategy: :one_for_one]
)
end
end
# event_monitor.ex
defmodule EventMonitor do
use GenServer
def start_link(mgr), do: GenServer.start(__MODULE__, [mgr], [])
def init(mgr) do
:ok = add_handler(mgr)
{:ok, mgr}
end
def handle_info({:gen_event_EXIT, _handler, _reason}, mgr) do
:ok = add_handler(mgr)
{:noreply, mgr}
end
def add_handler(mgr) do
GenEvent.add_mon_handler(mgr, EventHandler, [])
end
end
# event_handler.ex
defmodule EventHandler do
use GenEvent
require Logger
def init(_), do: {:ok, {}}
def handle_event(event, state) do
Logger.info "received event #{inspect event}"
{:ok, state}
end
end
# send event
iex>GenEvent.notify(:event_manager, {:event, "stuff"})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment