subscriptionCount

The number of subscribers (active collectors) to this shared flow.

The integer in the resulting StateFlow is not negative and starts with zero for a freshly created shared flow.

This state can be used to react to changes in the number of subscriptions to this shared flow. For example, if you need to call onActive when the first subscriber appears and onInactive when the last one disappears, you can set it up like this:

sharedFlow.subscriptionCount
.map { count -> count 0 } // map count into active/inactive flag
.distinctUntilChanged() // only react to true<->false changes
.onEach { isActive -> // configure an action
if (isActive) onActive() else onInactive()
}
.launchIn(scope) // launch it

Usually, StateFlow conflates values, but subscriptionCount is not conflated. This is done so that any subscribers that need to be notified when subscribers appear do reliably observe it. With conflation, if a single subscriber appeared and immediately left, those collecting subscriptionCount could fail to notice it due to 0 immediately conflating the subscription count.