subscriptionCount

abstract val subscriptionCount: StateFlow<Int>

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

Sources

common source
Link copied to clipboard