All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.pro.respawn.flowmvi.modules.StateModule.kt Maven / Gradle / Ivy

Go to download

A Kotlin Multiplatform MVI library based on plugins that is simple, fast, powerful & flexible

There is a newer version: 3.0.0
Show newest version
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) } }
}