Kiryl Tkach
Kiryl Tkach

Reputation: 3644

Deliver the first item as soon as it comes, debounce the following items

This question is the same like this and this, but about Kotlin flow.

What needs to be achieved:

Upvotes: 7

Views: 1540

Answers (3)

nilsi
nilsi

Reputation: 10761

I would make an extension function on Flow for this:

fun <T> Flow<T>.debounceEmitFirst(delayMillis: Long): Flow<T> {
    var firstEmission = true
    return this
        .debounce {
            if (firstEmission) {
                firstEmission = false
                0L
            } else {
                delayMillis
            }
        }
}

Upvotes: 0

user1071762
user1071762

Reputation: 685

What about

flow.withIndex().debounce {
    if(it.index == 0) {
        0L
    } else {
        1000L // your custom delay
    }
}.map {
    it.value
}

Upvotes: 5

Kiryl Tkach
Kiryl Tkach

Reputation: 3644

There is simple solution with dynamic debounce timeout:

var firstEmission = true
flow.debounce {
    if (firstEmission) {
        firstEmission = false
        0L
    } else DEBOUNCE_TIMEOUT
}

Also possible to do this way:

merge(
    flow.take(1),
    flow.drop(1).debounce(DEBOUNCE_TIMEOUT)
)

Upvotes: 7

Related Questions