debounce and conflate
- Kotlin course
- Advanced
- Lesson 10/83
- 5 min
Learn stream control with debounce and conflate.
debounce and conflate
debounce collapses rapid consecutive values in a flow. A value is emitted only when no new value arrives for a given duration; if one arrives, the previous is dropped.
conflate keeps only the latest value when the collector is slow, dropping intermediate ones. Use debounce for a search box that suggests as you type, and conflate for a fast sensor stream shown in the UI. Both reduce buffering needs on a flow.
debounce vs conflate
debounce is time based: it emits when no new value arrives for a given duration. It is useful for catching the pause when a user types, instead of processing every keystroke.
conflate is collector speed based. If the collector is busy with a value while the flow produces a new one, conflate skips the old and moves to the newest. Both boost performance but behave differently: debounce looks at time, conflate looks at the collector.
Practice Collect a flow with conflate
Write flowOf(1, 2, 3).conflate().collect { value -> println("Value: $value") }. You will see each value printed.
Starter code
// A flow with conflate
// write here
fun main() = runBlocking {
}Sample solution
fun main() = runBlocking {
flowOf(1, 2, 3).conflate().collect { value ->
println("Value: $value")
}
}Expected output
Value: 1 Value: 2 Value: 3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the debounce call
flow.____(100)
flow.debounce(100)
Explanation: debounce collapses rapid values.
2 What does conflate do?
- Cancels all values
- Keeps the latest value Correct answer
- Stops the flow
- Waits for each value
Explanation: conflate keeps the latest value for a slow collector.
3 Match debounce and conflate
| Term | Meaning |
|---|---|
debounce |
Time based |
conflate |
Collector speed based |
intermediate |
Dropped |
latest value |
Kept |