Skip to content

Instantly share code, notes, and snippets.

@abhimuktheeswarar
Last active August 6, 2021 06:15
Show Gist options
  • Select an option

  • Save abhimuktheeswarar/515a11b950c3fdd4d6087a5725ae0f82 to your computer and use it in GitHub Desktop.

Select an option

Save abhimuktheeswarar/515a11b950c3fdd4d6087a5725ae0f82 to your computer and use it in GitHub Desktop.
counterStateMachine for blog
fun CoroutineScope.counterStateMachine(
initialState: CounterState,
mutableStateFlow: MutableStateFlow<CounterState>,
mutableActions: MutableSharedFlow<CounterMessage>,
) =
actor<CounterMessage> {
var state: CounterState = initialState
channel.consumeEach { message ->
when (message) {
is IncrementCounter -> {
state = state.copy(count = state.count + 1)
mutableStateFlow.emit(state)
mutableActions.emit(message)
}
is DecrementCounter -> {
state = state.copy(count = state.count - 1)
mutableStateFlow.emit(state)
mutableActions.emit(message)
}
is GetCounterState -> message.deferred.complete(state)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment