GenNotify v0.3.0 GenNotify behaviour View Source

This is the main module that you will come in contact with.

you can use this module to inherit its functionality.

What is GenNotify

You can basically think of it as some kind of broadcast/multicast module. It's for forwarding Messages to everyone who is in the list of recipients.

Example

defmodule MyNotification do
  use GenNotify

  def on_message(msg) when is_binary(msg) do
    IO.puts("I got a message: #{msg}")
  end

  # we ignore all other kinds of messages
  def on_message(_msg), do: nil
end

To get up and running we do need to make sure that our Notifier is started.

GenNotify.Notifier.start_link()

Our Custom Notification has to be initialized at some point after GenNotify.Notifier. This will tell the Notifier to watch this Module

MyNotification.gen_notify_init()

somewhere else in the code...

GenNotify.send_notification("im a message") # => This will cause MyNotification.on_message/1 to be called

Example - GenServer

Sometimes a notification for a module isn't quite what you want. You want notifications for a specific Process. GenNotify does support GenServer

defmodule MyGenServer do
  use GenServer
  use GenNotify, gen_server: true # we need to tell GenNotify that this is indeed is a server

  def start_link(_) do
    GenServer.start_link(__MODULE__, :ok)
  end

  def init(_) do
    gen_notify_init() # => This will supply our PID to GenNotify.Notifier (Keep in mind, GenNotify.Notifier already needs to be alive!)
    {:ok, %{messages: 0}}
  end

  def on_message(msg, state) when is_binary(msg) do
    new_state = %{state | messages: state.messages + 1}
    IO.puts("#{msg} is my #{new_state.messages} message!") # => will be "im a message is my X message!" in our example
    new_state
  end

  # we ignore all other kinds of messages
  def on_message(_msg, state), do: state
end

somewhere else in the code...

GenNotify.send_notification("im a message")

Link to this section Summary

Callbacks

callback which will be invoked when a notification is sent via GenNotify.Notifier.send_notification/1 In case you use GenNotify, gen_server: true then on_message/2 will be called.

Link to this section Types

Link to this section Functions

Link to this section Callbacks

Link to this callback

on_message(msg)

View Source
on_message(msg()) :: any()

callback which will be invoked when a notification is sent via GenNotify.Notifier.send_notification/1 In case you use GenNotify, gen_server: true then on_message/2 will be called.

Link to this callback

on_message(msg, state)

View Source
on_message(msg(), state()) :: state()