-
-
Save pablisco/917168260db07abc17ce33bc9a4482e4 to your computer and use it in GitHub Desktop.
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
/** | |
* Returns a [SnapshotMutationPolicy] implementation that applies a debounce mechanism to mutation events. | |
* | |
* @param debounceTime The time window in milliseconds within which mutation events are considered to be the same. | |
* @return An instance of [SnapshotMutationPolicy] that applies a debounce mechanism. | |
* | |
* @param T The type of the snapshot. | |
*/ | |
fun <T> debounceMutationPolicy( | |
debounceTime: Long = 500, | |
): SnapshotMutationPolicy<T> = object : SnapshotMutationPolicy<T> { | |
var lastUpdate = 0L | |
override fun equivalent(a: T, b: T): Boolean = checkEquivalence(a, b).also { updateIfNeeded() } | |
private fun updateIfNeeded() = apply { if (isUpdateTime()) lastUpdate = now() } | |
private fun checkEquivalence(a: T, b: T): Boolean = if (isUpdateTime()) a == b else CancelMutation | |
private fun isUpdateTime() = now() - lastUpdate > debounceTime | |
} | |
/** | |
* Determines whether a mutation should be canceled or not. | |
* | |
* The value of this property determines whether a mutation should be canceled or not based on the conditions defined | |
* in the "checkEquivalence" function. | |
* If CancelMutation is set to `true`, the "checkEquivalence" function will return `true` if the time between the last | |
* update and the current time is greater than the debounce time. | |
* | |
* Otherwise, it will return the result of the equality comparison between the two provided values. | |
*/ | |
private const val CancelMutation = true |
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
mutableStateOf(initialValue, debounceMutationPolicy()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment