commonMain.pro.respawn.flowmvi.modules.StateModule.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of core-jvm Show documentation
Show all versions of core-jvm Show documentation
A Kotlin Multiplatform MVI library based on plugins that is simple, fast, powerful & flexible
package pro.respawn.flowmvi.modules
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.sync.Mutex
import pro.respawn.flowmvi.api.DelicateStoreApi
import pro.respawn.flowmvi.api.MVIState
import pro.respawn.flowmvi.api.StateProvider
import pro.respawn.flowmvi.api.StateReceiver
import pro.respawn.flowmvi.util.withReentrantLock
internal interface StateModule : StateReceiver, StateProvider
internal fun stateModule(initial: S): StateModule = StateModuleImpl(initial)
private class StateModuleImpl(initial: S) : StateModule {
private val _states = MutableStateFlow(initial)
private val stateMutex = Mutex()
@DelicateStoreApi
override val state by _states::value
@DelicateStoreApi
override fun useState(block: S.() -> S) = _states.update(block)
override val states: StateFlow = _states.asStateFlow()
override suspend fun withState(block: suspend S.() -> Unit) =
stateMutex.withReentrantLock { block(states.value) }
override suspend fun updateState(transform: suspend S.() -> S) =
stateMutex.withReentrantLock { _states.update { transform(it) } }
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy