Skip to content

Instantly share code, notes, and snippets.

@abhimuktheeswarar
Last active July 17, 2021 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhimuktheeswarar/d0b3b52dea831e95ee23e9dfcfe132f1 to your computer and use it in GitHub Desktop.
Save abhimuktheeswarar/d0b3b52dea831e95ee23e9dfcfe132f1 to your computer and use it in GitHub Desktop.
Actor based simple StateMachine
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