GenNotify v0.4.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.
A small Warning
Please be aware that this module can cause a lot of harm if misused. Sending a lot of Notifications to all kinds of recipients can make the your System very messy and it will be very annoying to debug.
TL;DR Do yourself and your colleagues a favor: Don't use this extensively!
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
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 GenServer
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.Supervisor 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
# Give the updated state back to the GenServer
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
delegation to GenNotify.Notifier.send_notification/1
Link to this section 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.