Skip to content

Instantly share code, notes, and snippets.

@abhimuktheeswarar
Last active July 17, 2021 15:08
Show Gist options
  • Save abhimuktheeswarar/d39230e59e8ecd9647b000e3b61c73e2 to your computer and use it in GitHub Desktop.
Save abhimuktheeswarar/d39230e59e8ecd9647b000e3b61c73e2 to your computer and use it in GitHub Desktop.
Simple store
class Store<S : State>(
initialState: S,
reduce: (Action, S) -> S,
val scope: CoroutineScope,
) {
private val inputActionsChannel: Channel<Action> =
Channel(capacity = Channel.UNLIMITED)
private val outputChannel: Channel<S> = Channel()
private val publishActions: MutableSharedFlow<Action> = MutableSharedFlow()
private val outputStateFlow: MutableStateFlow<S> = MutableStateFlow(initialState)
val actions: Flow<Action> = publishActions
val states: Flow<S> = outputStateFlow
init {
scope.stateMachine(
initialState = initialState,
inputActionsChannel = inputActionsChannel,
outputChannel = outputChannel,
publishActions = publishActions,
outputStateFlow = outputStateFlow,
reduce = reduce,
)
}
fun dispatch(action: Action) {
inputActionsChannel.trySend(action)
}
suspend fun getState(): S {
inputActionsChannel.send(RequestStateAction)
return outputChannel.receive()
}
fun terminate() {
scope.cancel()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment