Skip to Content
Course content

184: Flow Operators: debounce, distinctUntilChanged, flatMapLatest

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.