Pankaj Bagwan
Pankaj Bagwan
1 min read



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, [] }

  def handle_event({:broadcast, x}, broadcasts) do
    { :ok, [ x | broadcasts ] }

  def handle_call(:broadcasts, broadcasts) do
    {:ok, broadcasts, []}

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

#initiate a gen_event server
{:ok, pid} = :gen_event.start_link

Since we can not directly call or initiate our broadcast handler, we need to register it with event server

#add hadler to it
:gen_event.add_handler(pid, BroadcastEventHandler, [])

Now our broadcast handler is up and running and ready to receive broadcast messages

:gen_event.notify(pid, {:broadcast, "I dare you!"})
:gen_event.notify(pid, {:broadcast, "Meetup at 10 o'clock"})

So we published two messages to broadcast handler, lets see if it serves them well., BroadcastEventHandler, :broadcasts)
#=> ["Meetup at 10 o'clock", "I dare you!"], BroadcastEventHandler, :broadcasts)
#=> []

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.

:gen_event.notify(pid, {:broadcast, "Assemble in class"}), BroadcastEventHandler, :broadcasts)
#=> ["Assemble in class"]

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