-
-
Save belinwu/b37bfa42057af2851459896ea29bed7d to your computer and use it in GitHub Desktop.
Simple example how events can be debounced on StateMachine side
This file contains hidden or 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
// 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