EventManager v0.2.0 EventManager View Source

The event manager dispatches events to subscribers and adds some syntactic sugar as well as helpers on top of elixir's Registry.

It can also help reduce code complexity and lib coupling.

Link to this section Summary

Functions

Dispatch my event to every registered subscriber.

Return the registry name used by EventManager.

Start the registry and register static subscriptions.

Start subscriptions.

Subscribe to an event.

Unsubsribe from the specified event.

Link to this section Functions

Link to this function

dispatch(event_name, event_data)

View Source

Specs

dispatch(String.t(), any()) :: :ok

Dispatch my event to every registered subscriber.

The dispatch function will call all Modules/functions that have subscribed to the dispatch event. You can also add some data useful for managing the event in callbacks.

For example, if you want to dispatch an event when a new user is created, it could be nice to send the user in the event payload.

E.g.

iex> user = %{id: 1234, name: "Foo Bar", email: "foo@bar.com"}
iex> EventManager.dispatch("user_created", %{user: user})
iex> EventManager.dispatch("user_created", user)

Basically you can send whatever you want as a payload.

Return the registry name used by EventManager.

Start the registry and register static subscriptions.

opts accepts :

  • :apps: The application name that you want to use in the EventManager.

E.g

iex> EventManager.start_link(apps: [MyApp])
Link to this function

start_subscriptions(apps)

View Source

Specs

start_subscriptions([atom()]) :: {:ok, pid()}

Start subscriptions.

This function is automatically called if you use EventManager.start_link/1, but it's nice to know that you can call it manually depending on your needs.

E.g.

iex> EventManager.start_link([MyApp])

Specs

subscribe(String.t(), {atom(), atom() | String.t()}) :: :ok | :error

Subscribe to an event.

You can subscribe to an event by using the @subscribe attribute. To use it, first you must use EventManager.Handler.

E.g.

  defmodule MyApp do
    use EventManager.Handler

    @subscribe "event_1"
    def on_event_1(pid, payload) do
      # business logic
    end

    @subscribe event: "event_2", callback: "my_callback"
    def my_callback(pid, payload) do
      # business logic
    end
  end

pid is the id of the process that subscribes to the event. payload is the data that has been dispatched.

You can also subscribe dynamically (during runtime) using this function directly.

E.g

iex> EventManager.subscribe("event_name", {MyApp, :callback})
:ok

Specs

unsubscribe(String.t()) :: :ok

Unsubsribe from the specified event.

It can be very useful for async systems that are used by multiple PIDs for example. It's higly recommended that you only use it for dynamic subscriptions (see EventManager.subscribe/2)

It will only unsubscribe the event for the calling PID.

E.g.

iex> EventManager.unsubscribe("my_event_name")