Skip to content

Publish subscribe with gproc

Alexander Burkov edited this page Jan 13, 2015 · 3 revisions

Gproc properties offer a very simple way of doing publish/subscribe:

subscribe(Event) ->
    gproc:reg({p, l, {?MODULE, Event}}).
    
publish(Event, Data) ->
    gproc:send({p, l, {?MODULE, Event}}, {?MODULE, Event, Data}).

Remember that properties are non-unique, so each process can have one. The function gproc:send(Key, Msg) can either take a (unique) name as first argument, or a property. In the latter case, it will send Msg to each process that has that property.

Obviously the above code needs some checks, and perhaps some tweaking of the format of the notification being sent, but you get the point.

If a global property is used, the pub/sub pattern works across a cluster of nodes.

A benefit of using gproc this way, is that you can use the gproc query interface to check which processes subscribe to a given event. Also, when inspecting a specific process using e.g. gproc:info/1, you can tell much from its gproc properties. Choosing property names carefully makes them serve as runtime documentation of the responsibilities and dependencies of a process.