Skip to content

Instantly share code, notes, and snippets.

@joakimk joakimk/code.exs
Last active Aug 29, 2015

Embed
What would you like to do?
Simple example of using GenEvent to pass on messages
# In this example we're running jobs of some kind, and waiting for events if they finish okay or fail.
defmodule JobEvent do
def start_link do
{:ok, pid} = GenEvent.start_link(name: __MODULE__)
end
defmodule MessageForwarder do
use GenEvent
def handle_event(event, [listener]) do
send listener, event
{:ok, [listener]}
end
end
def subscribe do
GenEvent.add_handler(__MODULE__, MessageForwarder, [self])
end
def unsubscribe do
GenEvent.remove_handler(__MODULE__, MessageForwarder, [self])
end
def finished(job) do
notify {:finished, job}
end
def failed(job) do
notify {:failed, job}
end
defp notify(event) do
:ok = GenEvent.notify(__MODULE__, event)
end
end
# NOTE: we assume JobEvent is started by a supervisor somewhere
setup do
JobEvent.subscribe
# unsubscribe after each test so that events will work with multiple tests
on_exit &JobEvent.unsubscribe/0
end
test "..." do
job = %{...}
# call some code that eventually calls, JobEvent.finished(job)
assert_receive {:finished, job}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.