debounce

fun <T> Flow<T>.debounce(timeoutMillis: Long): Flow<T>(source)

Returns a flow that mirrors the original flow, but filters out values that are followed by the newer values within the given timeout. The latest value is always emitted.

Example:

flow {
    emit(1)
    delay(90)
    emit(2)
    delay(90)
    emit(3)
    delay(1010)
    emit(4)
    delay(1010)
    emit(5)
}.debounce(1000)

produces the following emissions

3, 4, 5

Note that the resulting flow does not emit anything as long as the original flow emits items faster than every timeoutMillis milliseconds.


fun <T> Flow<T>.debounce(timeoutMillis: (T) -> Long): Flow<T>(source)

Returns a flow that mirrors the original flow, but filters out values that are followed by the newer values within the given timeout. The latest value is always emitted.

A variation of debounce that allows specifying the timeout value dynamically.

Example:

flow {
    emit(1)
    delay(90)
    emit(2)
    delay(90)
    emit(3)
    delay(1010)
    emit(4)
    delay(1010)
    emit(5)
}.debounce {
    if (it == 1) {
        0L
    } else {
        1000L
    }
}

produces the following emissions

1, 3, 4, 5

Note that the resulting flow does not emit anything as long as the original flow emits items faster than every timeoutMillis milliseconds.

Parameters

timeoutMillis

T is the emitted value and the return value is timeout in milliseconds.


Returns a flow that mirrors the original flow, but filters out values that are followed by the newer values within the given timeout. The latest value is always emitted.

Example:

flow {
    emit(1)
    delay(90.milliseconds)
    emit(2)
    delay(90.milliseconds)
    emit(3)
    delay(1010.milliseconds)
    emit(4)
    delay(1010.milliseconds)
    emit(5)
}.debounce(1000.milliseconds)

produces the following emissions

3, 4, 5

Note that the resulting flow does not emit anything as long as the original flow emits items faster than every timeout milliseconds.


@JvmName(name = "debounceDuration")
fun <T> Flow<T>.debounce(timeout: (T) -> Duration): Flow<T>(source)

Returns a flow that mirrors the original flow, but filters out values that are followed by the newer values within the given timeout. The latest value is always emitted.

A variation of debounce that allows specifying the timeout value dynamically.

Example:

flow {
    emit(1)
    delay(90.milliseconds)
    emit(2)
    delay(90.milliseconds)
    emit(3)
    delay(1010.milliseconds)
    emit(4)
    delay(1010.milliseconds)
    emit(5)
}.debounce {
    if (it == 1) {
        0.milliseconds
    } else {
        1000.milliseconds
    }
}

produces the following emissions

1, 3, 4, 5

Note that the resulting flow does not emit anything as long as the original flow emits items faster than every timeout unit.

Parameters

timeout

T is the emitted value and the return value is timeout in Duration.