Skip to content

Instantly share code, notes, and snippets.

@faruktoptas
Created March 5, 2020 06:28
Show Gist options
  • Save faruktoptas/c45272047fae8da61acfb7b14c451793 to your computer and use it in GitHub Desktop.
Save faruktoptas/c45272047fae8da61acfb7b14c451793 to your computer and use it in GitHub Desktop.
Kotlin coroutine debounce for EditText
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)
@ooxoxx
Copy link

ooxoxx commented Dec 13, 2023

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