How to check if there are subscriptions to a broadcast?

Hi, in my Rails view I’m using turbo_stream_from to subscribe to a turbo stream broadcast to display a list of patients:

<%= turbo_stream_from :all_patients_broadcast %>

I want this list to be updated when a new patient is created, so I call:

constly_method

Turbo::StreamsChannel.broadcast_update_to(:all_users_broadcast,...)

However, I want to run constly_method only if there are any clients that are actually subscribed to :all_patients_broadcast at the moment. Is there any way to check that?

You can use the “PUBSUB CHANNELS” redis command: PUBSUB CHANNELS | Redis

Give this a try:

subs = ActionCable.server.pubsub.send(:redis_connection).pubsub('channels', "all_users_broadcast")

if subs.size > 0
  costly_method
end

You can also do the following:

after_create_commit do
  return unless costly_method

  broadcast_update_to(:all_users_broadcast,...)
end