Last active
July 17, 2021 15:08
-
-
Save abhimuktheeswarar/d39230e59e8ecd9647b000e3b61c73e2 to your computer and use it in GitHub Desktop.
Simple store
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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