stateInWhileSubscribed

fun <T> Flow<T>.stateInWhileSubscribed(scope: CoroutineScope, initialValue: T, stopTimeoutMillis: Long, replayExpirationMillis: Long = Long.MAX_VALUE): StateFlow<T>(source)

Converts this flow into a StateFlow that only runs upstream while it has subscribers, plus a stopTimeoutMillis grace period after the last one leaves.

It is stateIn(scope, SharingStarted.WhileSubscribed(stopTimeoutMillis, replayExpirationMillis), initialValue). The default of 5_000 ms is the value recommended by FLOW_006: it keeps work alive across short interruptions such as Android configuration changes, without keeping upstream running forever like SharingStarted.Eagerly. initialValue is visible before the first upstream emission, and upstream restarts when a new subscriber appears after it stopped.

Example:

val items: StateFlow<List<Item>> = repository.observeItems()
.stateInWhileSubscribed(viewModelScope, initialValue = emptyList())

Rules: FLOW_006 (stateIn with Eagerly on a lifecycle scope). See docs/BEST_PRACTICES_COROUTINES.md section 9.7.

Requires opting in to ExperimentalStructuredCoroutines.

Receiver

the upstream flow to share.

Return

a StateFlow holding the latest upstream value.

Parameters

scope

the scope that owns the sharing coroutine; cancelling it stops the StateFlow updates.

initialValue

value exposed before the first upstream emission.

stopTimeoutMillis

delay, in milliseconds, before upstream is stopped after the last subscriber leaves.

replayExpirationMillis

delay, in milliseconds, before the replayed value is reset after upstream stops; Long.MAX_VALUE keeps it forever.

See also