Pubsub system, where I know more about the subscribers

Hi,

I am looking for a way to create a pubsub system where the publisher has a little bit more control over the subscribers:

  • depending on the state of the publisher, I want to send a “welcome” message to every new subscriber, informing them about some aspects of the publisher state.
  • The publisher does some heavy computing, but if there are no subscribers it shall stop. So it would be nice if it could know if any subscribers are there.

Being very new to Elixir, I am trying to figure out a good way to do this.
First I tried :pg2, but that seems to not exist anymore in OTP24.

Can Phoenix.PubSub be convinced to five me this information?
Or what can I use to replace :pg2.

Thanks for any hints :slight_smile:

I will not comment on your bigger goal but :pg2 got replaced by :pg – so you could check that out.

1 Like

I’m pretty sure you could just use Phoenix.PubSub out of the box. Perusing the pg2 adapter module, it does check for :pg first.

Just generally speaking you could do something like:

Phoenix.PubSub.subscribe(MyApp.PubSub, "user")
Phoenix.PubSub.broadcast(MyApp.PubSub, "user", :welcome_message)

Phoenix.Tracker.list(MyApp.PubSub, "user")

I found this book by @sb8244 really helpful.

3 Likes

Oh, interessting. I have seen :pg. But bebause it is kind of unintuitive, that :pg replaced :pg2 and not the other way around, I did not think of it.
Thanks for the hint!

1 Like

Thanks for the advice! The book looks very interesting, I will put it on my reading list.
The Phoenix Tracker list function I was also not aware of, that is very useful to me.

But I am also a little confused. In your example, the :welcome_message would get send to any subscriber whenever any new subscriber arrives, right?
Just checking,if I understand correctly.

But I could just write an explicit subscribe function and send an initial message to the process that just subscribed.

Thanks for the help!.

Yes in that example it would get sent to everyone.

The convention is to have topics delimited by a colon.

So you could subscribe the user, roadrunner, to “user:acme:roadrunner” to track users by company, so you could broadcast a message to all users, all users working at acme or just roadrunner.

You could use pg:monitor_scope or pg:monitor.
Then you get a message whenever a process leaves or joins.
pg is very flexible, you can have multiple scopes, group names can be any term.