Is there any more efficient pattern for preserving...
# flow
d
Is there any more efficient pattern for preserving the stateful nature of a
StateFlow
after e.g. after performing regular
Flow
transforming operations on it. e.g. to map a
StateFlow
and keep the output as a
StateFlow
, I often employ a pattern like:
Copy code
val isSwitchEnabledFlow: StateFlow<Boolean> by lazy {
        fun isSwitchable(state: ScreenState) = state is SwitchableState // Any mapping
        screenStateFlow
            .map(::isSwitchable) // Apply mapping for new values
            .stateIn(
                scope = this,
                started = SharingStarted.Eagerly,
                initialValue = isSwitchable(screenStateFlow.value) // Apply mapping for initial value
            )
    }
...key point is defining the mapping as a privately scoped function to use in both the
map
and
initialValue
. Any more concise form I've missed?