SharingStarted

fun interface SharingStarted(source)

A strategy for starting and stopping the sharing coroutine in shareIn and stateIn operators.

This functional interface provides a set of built-in strategies: Eagerly, Lazily, WhileSubscribed, and supports custom strategies by implementing this interface's command function.

For example, it is possible to define a custom strategy that starts the upstream only when the number of subscribers exceeds the given threshold and make it an extension on SharingStarted.Companion so that it looks like a built-in strategy on the use-site:

fun SharingStarted.Companion.WhileSubscribedAtLeast(threshold: Int) =
SharingStarted { subscriptionCount: StateFlow<Int> ->
subscriptionCount.map { if (it >= threshold) SharingCommand.START else SharingCommand.STOP }
}

Commands

The SharingStarted strategy works by emitting commands that control upstream flow from its command flow implementation function. Back-to-back emissions of the same command have no effect. Only emission of a different command has effect:

Initially, the upstream flow is stopped and is in the initial state, so the emission of additional STOP and STOP_AND_RESET_REPLAY_CACHE commands will have no effect.

The completion of the command flow normally has no effect (the upstream flow keeps running if it was running). The failure of the command flow cancels the sharing coroutine and the upstream flow.

Types

Link copied to clipboard
object Companion

Functions

Link copied to clipboard
abstract fun command(subscriptionCount: StateFlow<Int>): Flow<SharingCommand>

Transforms the subscriptionCount state of the shared flow into the flow of commands that control the sharing coroutine. See the SharingStarted interface documentation for details.