Skip to content

Instantly share code, notes, and snippets.

@patjackson52
Created April 7, 2020 19:05
Show Gist options
  • Select an option

  • Save patjackson52/744001821644161c6dbb8ae9ad352b92 to your computer and use it in GitHub Desktop.

Select an option

Save patjackson52/744001821644161c6dbb8ae9ad352b92 to your computer and use it in GitHub Desktop.
A threadsafe wrapper of ReduxKotlin store. Multiplatform compatible.
/**
* Threadsafe wrapper for ReduxKotlin store that synchronizes access to each function using
* kotlinx.AtomicFu [https://github.com/Kotlin/kotlinx.atomicfu]
* Allows all store functions to be accessed from any thread.
* This does have a performance impact for JVM/Native.
* For use with [https://ReduxKotlin.org]
*/
class SynchronizedStore<TState>(val store: Store<TState>) : Store<TState>, SynchronizedObject() {
override var dispatch: Dispatcher = { action ->
synchronized(this) { store.dispatch(action) }
}
override val getState: GetState<TState> = {
synchronized(this) { store.getState() }
}
override val replaceReducer: (Reducer<TState>) -> Unit = { reducer ->
synchronized(this) { store.replaceReducer(reducer) }
}
override val subscribe: (StoreSubscriber) -> StoreSubscription = { storeSubscriber ->
synchronized(this) { store.subscribe(storeSubscriber) }
}
}
@patjackson52
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment