Skip to content

Instantly share code, notes, and snippets.

@linean
Created February 9, 2023 10:49
Show Gist options
  • Save linean/eeb6ed53770f9dc5b757b3bc1e8b0797 to your computer and use it in GitHub Desktop.
Save linean/eeb6ed53770f9dc5b757b3bc1e8b0797 to your computer and use it in GitHub Desktop.
Simple example how events can be debounced on StateMachine side
// Keep in mind this is just simplified example
class Example {
private val scope = CoroutineScope(Job())
private val debouncingChannel = Channel<UserEvent>(
capacity = RENDEZVOUS,
onBufferOverflow = BufferOverflow.DROP_OLDEST,
)
val stateMachine = StateMachine(
initialState = Unit,
reduceState = ::reduceState
)
init {
// You can have more sophisticated debouncing logic here
debouncingChannel.receiveAsFlow()
.debounce(timeoutMillis = 200)
.onEach { stateMachine.handleEvent(DebouncedUserEvent) }
.launchIn(scope)
}
private fun reduceState(
currentState: Unit,
event: Event
) {
when (event) {
is UserEvent -> {
debouncingChannel.trySend(event)
}
is DebouncedUserEvent -> {
// modify state here
}
}
}
interface Event {
object UserEvent : Event
object DebouncedUserEvent : Event
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment