KDebouncer

class KDebouncer<T>(scope: CoroutineScope, val delay: Duration = 300.milliseconds, val leading: Boolean = false)(source)

A coroutine-based debouncer that delays forwarding values until no new values have arrived for the specified delay duration.

This is typically used for search fields, auto-saves, or any input-triggered actions that should only execute after the user has stopped typing.

Basic usage (Flow-based)

val debouncer = KDebouncer<String>(scope = viewModelScope, delay = 300.milliseconds)

// Emit from a text-field's onValueChange:
onValueChange = { text -> debouncer.emit(text) }

// Collect the stable values:
viewModelScope.launch {
debouncer.flow.collect { stableText -> search(stableText) }
}

Callback-style usage

val debouncer = KDebouncer<String>(scope = viewModelScope)
debouncer.onDebounced { query -> viewModel.search(query) }

// Then in UI:
onValueChange = { debouncer.emit(it) }

Parameters

scope

The CoroutineScope in which the debouncing coroutine runs.

delay

The quiet period duration before a value is forwarded. Default: 300ms.

leading

If true, emit the first value immediately and suppress subsequent values until the quiet period elapses. Default: false.

Type Parameters

T

The type of values being debounced.

Constructors

Link copied to clipboard
constructor(scope: CoroutineScope, delay: Duration = 300.milliseconds, leading: Boolean = false)

Properties

Link copied to clipboard
Link copied to clipboard
val flow: Flow<T>

Debounced output — collect this to receive stable values.

Link copied to clipboard

Functions

Link copied to clipboard
fun cancel()

Cancels the internal callback job (if any). Does not cancel the scope.

Link copied to clipboard
fun emit(value: T)

Sends a new value into the debouncer.

Link copied to clipboard
fun onDebounced(block: suspend (T) -> Unit)

Registers a suspending block that is called each time a debounced value arrives. Replaces any previously registered callback.