So very first behaviour server of OTP that we are gonna look in is Generic(I am guessing what gen means in erlang) event server.
Okay Jack! first we look at, as how a event server should look like. Event server are abled to
1.) receive certain event they are bind to,
2.) notify listner bound/subscribed to those events/listner (or client) should consume those event as and when they happen.
That’s it! To understand this behaviour we will build a broadcast event server.
defmodule BroadcastEventHandler do
use GenEvent.Behaviour
def init(_) do
{ :ok, [] }
end
def handle_event({:broadcast, x}, broadcasts) do
{ :ok, [ x | broadcasts ] }
end
def handle_call(:broadcasts, broadcasts) do
{:ok, broadcasts, []}
end
end
This is it. We defined out intial version of broadcast server. It has two method apart from intializer. One to receive published event, another one to list all event that happened since last conversation with subscriber.
Jack is dying to use it. Let’s look how to use it
1.) We need to initiate a gen_event
server. This will return tuple of {:ok, pid}
as a response
Since we can not directly call or initiate our broadcast handler, we need to register it with event server
Now our broadcast handler is up and running and ready to receive broadcast messages
So we published two messages to broadcast handler, lets see if it serves them well.
Well done boy! It only served them once, when we called again, it returned empty array, as messages were already consumed. Lets do one more round.
Great going Jack!
About The Author
I am Pankaj Baagwan, a System Design Architect. A Computer Scientist by heart, process enthusiast, and open source author/contributor/writer. Advocates Karma. Love working with cutting edge, fascinating, open source technologies.
To consult Pankaj Bagwan on System Design, Cyber Security and Application Development, SEO and SMO, please reach out at me[at]bagwanpankaj[dot]com
For promotion/advertisement of your services and products on this blog, please reach out at me[at]bagwanpankaj[dot]com
Stay tuned <3. Signing off for RAAM