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

commonMain.org.reduxkotlin.CreateSameThreadEnforcedStore.kt Maven / Gradle / Ivy

The newest version!
package org.reduxkotlin

import org.reduxkotlin.utils.getThreadName
import org.reduxkotlin.utils.stripCoroutineName

/**
 * Creates a Redux store that can only be accessed from the same thread.
 * Any call to the store's functions called from a thread other than thread
 * from which it was created will throw an IllegalStateException.
 *
 * Most use cases will want to use [createThreadSafeStore] or [createStore]
 * More details:   TODO add documentation link
 *
 * see [createStore] for details on store params/behavior
 */
fun  createSameThreadEnforcedStore(
    reducer: Reducer,
    preloadedState: State,
    enhancer: StoreEnhancer? = null
): Store {

    val store = createStore(reducer, preloadedState, enhancer)
    val storeThreadName = stripCoroutineName(getThreadName())
    fun isSameThread() = stripCoroutineName(getThreadName()) == storeThreadName
    fun checkSameThread() = check(isSameThread()) {
        """You may not call the store from a thread other than the thread on which it was created.
            |This includes: getState(), dispatch(), subscribe(), and replaceReducer()
            |This store was created on: '$storeThreadName' and current
            |thread is '${getThreadName()}'
            """.trimMargin()
    }

    return object : Store {
        override val getState = {
            checkSameThread()
            store.getState()
        }

        override var dispatch: Dispatcher = { action ->
            checkSameThread()
            store.dispatch(action)
        }

        override val subscribe = { storeSubscriber: StoreSubscriber ->
            checkSameThread()
            store.subscribe(storeSubscriber)
        }

        override val replaceReducer = { reducer: Reducer ->
            checkSameThread()
            store.replaceReducer(reducer)
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy