Created
March 5, 2020 06:28
-
-
Save faruktoptas/c45272047fae8da61acfb7b14c451793 to your computer and use it in GitHub Desktop.
Kotlin coroutine debounce for EditText
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
fun <T> debounce( | |
waitMs: Long = 300L, | |
scope: CoroutineScope, | |
destinationFunction: (T) -> Unit | |
): (T) -> Unit { | |
var debounceJob: Job? = null | |
return { param: T -> | |
debounceJob?.cancel() | |
debounceJob = scope.launch { | |
delay(waitMs) | |
destinationFunction(param) | |
} | |
} | |
} | |
val debounceTextChange = debounce(300L, viewModel.viewModelScope, viewModel::search) | |
editText.onChange(debounceTextChange) |
thank you very for inspiring me. I made some state sharing improvement for those who need the very same functionality but in a race condition:
@OptIn(ExperimentalCoroutinesApi::class, DelicateCoroutinesApi::class)
private fun <T> debounce(
waitMs: Long = 300L,
scope: CoroutineScope,
destinationFunction: (T) -> Unit
): (T) -> Unit {
var debounceJob: Job? = null
val context = newSingleThreadContext("Debounce")
return { param: T ->
scope.launch {
withContext(context) {
debounceJob?.cancel()
debounceJob = scope.launch {
delay(waitMs)
destinationFunction(param)
}
}
}
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
fantastic! thanks a lot