BBHoss

A brief history of my experiences in programming & system operations

Easy Pub-sub Event Dispatch with :gproc and Elixir

Posted at — Oct 8, 2015

Prologue

I recently came across the need to do pubsub inside of one of my Elixir applications. Initially I hand-rolled a system using GenEvent, but after I finished I realized how brittle the system was, even with all of the handholding I was doing with add_mon_handler. I was already using :gproc for a process registry, when I remembered reading something about it being able to do pubsub.

:gproc is Awesome

For my application, I needed to publish a message and have it received by multiple subscribers. Textbook pubsub, ok? Here’s a quick and dirty demo of what that looks like. So that’s fairly cool, although it would be even cooler if we could use the GenServer functions like they were intended. Luckily OTP can handle that!

OTP is Awesome

Thanks to a helpful tip and some handholding by fishcakez on IRC, I was able to use the GenServer functions as intended. It turns out that most of OTP’s generic implementations support what’s called a via tuple, which is shown below.

Conclusion

Using the cool tool :gproc along with the extremely well designed OTP libraries allows you to do process lookup and dispatch in an elegant and easy way. I would like to be able to call some of the synchronous functions like this, but I haven’t figured out a way to do it without just looking up the processes manually using :gproc and calling manually. If you figure out how, let me know!

comments powered by Disqus