[erlang-questions] conditional pub-sub in gproc

Ulf Wiger ulf@REDACTED
Fri Jun 15 20:33:25 CEST 2012

I threw in a function for doing pub/sub with simple filter conditions in gproc.


A simple example:

Eshell V5.9  (abort with ^G)
1> application:start(gproc).

%% Subscribe to level changes for a gauge; only report if Level > 3

2> gproc_ps:subscribe_cond(l,gauge,ets:fun2ms(fun({level,N}) when N > 3 -> true end)).

3> gproc_ps:publish_cond(l,gauge,{level,1}).
4> flush().
ok		% no message delivered

5> gproc_ps:publish_cond(l,gauge,{level,4}).
6> flush().                                 
Shell got {gproc_ps_event,gauge,{level,4}}

Essentially, gproc attaches a match_spec to the subscription entry, and this
match_spec is evaluated when each event is published.

If ets:match_spec_run([Msg], ets:match_spec_compile(Condition)) == [true],
the message is delivered; otherwise not.

The match specs are stored un-compiled, partly because you can't pass
compiled match specs between nodes (gproc's global scope), and partly
because you can't read them when compiled, and it's useful to be able to
inspect properties:

7> gproc:info(self()).

Feedback is welcome.

Ulf W

Ulf Wiger, Co-founder & Developer Advocate, Feuerlabs Inc.

More information about the erlang-questions mailing list