Last active
August 6, 2021 06:15
-
-
Save abhimuktheeswarar/515a11b950c3fdd4d6087a5725ae0f82 to your computer and use it in GitHub Desktop.
counterStateMachine for blog
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 CoroutineScope.counterStateMachine( | |
initialState: CounterState, | |
mutableStateFlow: MutableStateFlow<CounterState>, | |
mutableMessages: 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) | |
mutableMessages.emit(message) | |
} | |
is DecrementCounter -> { | |
state = state.copy(count = state.count - 1) | |
mutableStateFlow.emit(state) | |
mutableMessages.emit(message) | |
} | |
is GetCounterState -> message.deferred.complete(state) | |
} | |
} | |
} | |
class CounterStateStore(initialState: CounterState, val scope: CoroutineScope) { | |
private val mutableStateFlow = MutableStateFlow<CounterState>(initialState) | |
private val mutableMessages = MutableSharedFlow<CounterMessage>() | |
private val stateMachine = | |
scope.counterStateMachine(initialState, mutableStateFlow, mutableMessages) | |
val stateFlow: Flow<CounterState> = mutableStateFlow | |
val messagesFlow: Flow<CounterMessage> = mutableMessages | |
fun dispatch(message: CounterMessage) { | |
stateMachine.trySend(message) | |
} | |
suspend fun getState(): CounterState { | |
val completableDeferred = CompletableDeferred<CounterState>() | |
dispatch(GetCounterState(completableDeferred)) | |
return completableDeferred.await() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment