Getting the number of subscribers after an Endpoint.subscribe

After and Endpoint.subscribe I would like to be able to get the number of subscribers to the topic.

My use case is this.

A person wants to get realtime upates for a train station they are at.
They subscribe to that station and I have Gen Server to go fetch that data every 5 seconds from an api.

A second person arrives at the same station and subscribes.

I still only need to fetch that data once to serve both people.

A third person arrives at a different station and subscribes.

I now have a list of of two stations to fetch realtime data from (stored in state in the gen server).

This third person closes their browser and unsubscribes but the gen server doesn’t know if this is the last subscribe and so still has to fetch the data for the second station to broadcast even though there are no subscribers.

If I knew there were no subscribers I could remove the second station from the list.

I have tried IO.inspect(Phoenix.Local.subscribers(Metro.PubSub, topic, 0))

I have considered having an increment decremement in the gen server state but this is two sources of truth and complicates the management

This is (amongst other things) what Phoenix presence was designed to solve. This problem space isn’t simple once multiple nodes get involved, and so Presence was created to try and to at least make it to use.

1 Like

And if you’re not multi node I’d suggest using Registry directly, which has APIs for counting registered processes in various ways.

2 Likes

In the end I adopted the inc/dec subscriber approach.

  %{
    stations: [
      %{
        name: "NSH",
        subscribers: 3
      },
    ]
  }

It is not ideal, but it works.

I am just not familiar enough with Elixir to go down the other route.

Appreciate your advice though