//reactivestate-core/com.ensody.reactivestate/stateOnDemand
stateOnDemand¶
[common]\ fun <T> Flow<T>.stateOnDemand(context: CoroutineContext = EmptyCoroutineContext, synchronous: Boolean = true, emitValueOnStart: Boolean = true, getter: (previous: Wrapped<T>?) -> T): StateFlow<T>
Turns this Flow into a StateFlow without requiring a CoroutineScope (unlike stateIn).
When the resulting StateFlow gets collected this in turn starts collecting this underlying Flow. When nobody collects, the StateFlow.value gets computed via getter which is also passed the previous value wrapped in a Wrapped instance or null if there is no previous value, yet. This way you can implement simple caching.
When nobody collects, this is safe for garbage collection.
Normally you’d use this together with callbackFlow, for example.