Disclaimer: I'm pretty new to Erlang and OTP.
I want a simple pubsub in Erlang / OTP, where processes can subscribe to some kind of "hub" and receive a copy of messages sent to this center.
I know about gen_event , but it processes events in a single event dispatcher process, while I want each subscriber to be a separate, standalone process. In addition, I could not get control of the gen_event handlers. Unfortunately, the Google results were full of XMPP (Ejabberd) and RabbitMQ connections, so I did not find anything that could be related to my idea.
My idea is that such a pubsub model can easily be mapped to a watch tree. So I decided to extend the supervisor (a gen_server under the hood) to send a broadcast message to all of my children.
I hacked this in my quick and dirty regular dispatcher behavior:
-module(dispatcher). -extends(supervisor). -export([notify/2, start_link/2, start_link/3, handle_cast/2]). start_link(Mod, Args) -> gen_server:start_link(dispatcher, {self, Mod, Args}, []). start_link(SupName, Mod, Args) -> gen_server:start_link(SupName, dispatcher, {SupName, Mod, Args}, []). notify(Dispatcher, Message) -> gen_server:cast(Dispatcher, {message, Message}). handle_cast({message, Message}, State) -> {reply, Children, State} = supervisor:handle_call(which_children, dummy, State), Pids = lists:filter(fun(Pid) -> is_pid(Pid) end, lists:map(fun({_Id, Child, _Type, _Modules}) -> Child end, Children)), [gen_server:cast(Pid, Message) || Pid <- Pids], {noreply, State}.
However, although everything seems to work fine at a glance (children receive messages and restart smoothly when they fail), I wonder when it was a good idea.
Can someone please criticize (or approve) my approach and / or recommend some alternatives?