Skip to content

Instantly share code, notes, and snippets.

@CostaFot
Last active April 21, 2025 20:58
Show Gist options
  • Save CostaFot/1d6781651bf76733c899e50ad4e0e6f4 to your computer and use it in GitHub Desktop.
Save CostaFot/1d6781651bf76733c899e50ad4e0e6f4 to your computer and use it in GitHub Desktop.
private class CooldownStateFlow<T>(
initialValue: T,
private val coroutineScope: CoroutineScope,
dispatcher: CoroutineDispatcher,
private val cooldownMillis: Long = 50L,
) {
private val singleThreadDispatcher = dispatcher.limitedParallelism(1)
private val _events =
MutableSharedFlow<T>().also {
coroutineScope.launch(singleThreadDispatcher) {
it.collect { value ->
_stateFlow.update { value }
delay(cooldownMillis)
}
}
}
private val _stateFlow = MutableStateFlow(initialValue)
val stateFlow = _stateFlow.asStateFlow()
fun update(value: T) {
coroutineScope.launch(singleThreadDispatcher) {
_events.emit(value)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment