Events/Observer pattern
Matthias Lang
matthias@REDACTED
Thu Nov 24 17:19:46 CET 2005
Corrado Santoro writes:
> Matthias Lang wrote:
> > I don't think there's anything in the standard library which does
> > that.
> Why? Don't you think that gen_event could exactly fit in the problem?
No, gen_event doesn't provide the interface he asked for. You have to
add code. Quite a bit of code.
How much code is needed to do this using gen_event? How much using
gen_server? I think it's the same: one data structure, one module, six
callback functions. I.e. gen_event provides no benefit, even in
an application it might be expected to be good at! No wonder it's not
used much.
FWIW, as is often the case, doing this in classic Erlang is neater and
simpler. Here's a no-frills version:
loop(Pids) ->
receive
{reg, Pid} -> loop([Pid|Pids]);
{unreg, Pid} -> loop([X || X <- Pids, X =/= Pid]);
{send, Msg} -> [ X ! Msg || X <- Pids], loop(Pids)
end.
Matthias
--------------------
> > doublec writes:
> >
> > > I want to have a process that sends information out to other
> > > processes at regular intervals. Those other processes should be
> > > able to register to receive information or unregister to stop
> > > receiving them. Classic 'observer' pattern stuff in OO.
> > >
> > > I thought of having the information provider process accept pid's
> > > on register, and when it needs to send out the information it just
> > > goes over the list of pid's sending a message to the receiver.
> > >
> > > Is that a reasonable approach? Is there anything in the standard
> > > library that provides this functionality already that I should be
> > > looking at?
More information about the erlang-questions
mailing list