Search code examples
kotlinkotlin-coroutineskotlin-flow

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:

  • Deliver the first item as soon as it comes
  • Debounce all the following items the way debounce function works

Solution

  • 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)
    )