Last active
April 21, 2025 20:58
-
-
Save CostaFot/1d6781651bf76733c899e50ad4e0e6f4 to your computer and use it in GitHub Desktop.
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
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