-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
184: Flow Operators: debounce, distinctUntilChanged, flatMapLatest
Listen, I've seen this bug in production a dozen times: a developer builds a search-as-you-type feature and thinks that adding distinctUntilChanged() is enough to keep the API from being hammered. They assume that if the user hasn't changed the text, the flow won't trigger a new request. On paper, that sounds logical. In practice, it's a recipe for a lagging UI and a stressed server.
The Myth: "distinctUntilChanged stops redundant searches"
Here is why that thinking fails. Imagine a user is searching for "Kotlin". They type "K", then "Ko", then they realize they made a mistake and hit backspace to go back to "K".
// The sequence of emissions:
"K" -> "Ko" -> "K"
If you only use distinctUntilChanged(), the flow sees "K", then it sees "Ko" (which is different), then it sees "K" again (which is also different from "Ko"). All three of these will trigger an API call. The operator only cares if the immediate previous value was the same. It has no memory of the history before that. If your user is a "jittery" typer—someone who corrects a typo instantly—you're still firing off way more requests than necessary.
The Reality: Orchestrating Time and Cancellation
To actually solve the search-bar problem, you need a trio of operators working in a specific order. You aren't just filtering values; you're managing time and concurrency.
First, we use debounce. This tells the flow: "Wait until the user has stopped typing for X milliseconds before you let this value through." This prevents a request on every single keystroke.
Next, we use distinctUntilChanged. Now that we've waited for the user to pause, we check if the resulting string is actually different from the last one we searched for. This handles the case where a user types a character and immediately deletes it within the debounce window.
Finally, the heavy hitter: flatMapLatest. This is the most critical part. Standard flatMapMerge or flatMapConcat would let previous search requests finish even if a new one started. flatMapLatest says: "If a new search term arrives while the previous network call is still running, cancel the previous call immediately. I only care about the latest result."
Here is how I actually implement this in a real project:
searchQueryFlow
.debounce(300) // Wait for a 300ms pause in typing
.distinctUntilChanged() // Only proceed if the text actually changed
.flatMapLatest { query ->
// If a new query comes in, the previous search block is cancelled
flow {
emit(searchApi.performSearch(query))
}
}
.collect { results ->
updateUi(results)
}
I like to think of flatMapLatest as a "ruthless" operator. It doesn't care about the effort the previous network call put in; if the user changed their mind, that old request is now garbage. Using it prevents the "race condition" where a slow response from a previous search arrives after a fast response from the current search, causing the UI to jump back to old results.
📋 Practical Task
Implementing a Responsive Movie Search Filter
You are building a movie discovery app. You have a StateFlow<String> called searchQuery that updates every time the user types in the search bar. You also have a suspending function movieService.searchMovies(query: String): List<Movie>.
Your goal is to create a Flow pipeline that:
- Ignores emissions that occur within 500ms of each other to avoid overloading the API.
- Prevents the same search term from being sent twice in a row.
- Ensures that if the user continues typing, any active network request for a previous term is cancelled immediately.
Write the implementation of the flow pipeline and collect the results to update a movieList variable.
There are no comments for now.