Last active
July 17, 2021 13:32
-
-
Save abhimuktheeswarar/d0b3b52dea831e95ee23e9dfcfe132f1 to your computer and use it in GitHub Desktop.
Actor based simple StateMachine
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
fun <S : State> CoroutineScope.stateMachine( | |
initialState: S, | |
inputActionsChannel: ReceiveChannel<Action>, | |
outputChannel: SendChannel<S>, | |
publishActions: MutableSharedFlow<Action>, | |
outputStateFlow: MutableStateFlow<S>, | |
reduce: (Action, S) -> S, | |
) = launch { | |
var state = initialState | |
inputActionsChannel.consumeEach { action -> | |
if (action !is RequestStateAction) { | |
state = reduce(action, state) | |
outputStateFlow.emit(state) | |
publishActions.emit(action) | |
} else { | |
outputChannel.send(state) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment