/Projects

Search-as-you-type with debounce and cancellation

One request per pause in typing, and never a stale result on screen.

PracticeMachine codingTier 2 · MechanismsCreate30 minMobile systems

You will be able to: build search-as-you-type with debounce and cancellation in 30 minutes, edge cases included.

Source: Tested in tests/mobile/MobileTests.kt

Mobile engineeringAll mobile pages

One-way data flow with a user typing: newer input cancels older work, so a stale answer can never overwrite a fresh one. Start from the basics in Day 9 →

Study with AI

30-minute round · MediumKotlin · coroutines · tested Watch as reels
Part 1 of 5

Basics

The concepts this component is built on. With these in mind, every line of the solution has a reason.

1.1Key concepts

One idea per card, in the order the solution uses them.

01Debounce

Wait until the user pauses typing before acting. Typing 'kotlin' sends one request, not six.

02Cancellation

When the query changes, the work for the old query stops, so no network or CPU is spent on results nobody will see.

03Stale responses

Responses can arrive out of order. A slow answer for 'kot' must never replace the answer for 'kotlin'.

04StateFlow and UI state

A StateFlow holds the current screen state and notifies the UI when it changes. One immutable SearchUi object keeps results, spinner and error consistent.

Part 2 of 5

Question

What exactly you are asked to build, what must be true when you are done, and what to ask before you start.

2.1Prompt

The question as the interviewer asks it, and the requirements to check your solution against.

Interviewer

Build the view model for a search box that queries the server as the user types. Do not hit the API on every keystroke, and never show results for an old query.

Requirements

  • Debounce keystrokes
  • Cancel in-flight work when the query changes
  • Ignore queries shorter than two characters
  • Expose loading and error state for the UI

2.2Clarify first

Questions worth asking, and the answers this interviewer gives.

You askInterviewer answers
How long a debounce?About 300 ms: long enough to skip mid-word requests, short enough to feel instant.
Cache results?A small in-memory cache keyed by query is a good follow-up.
Which scope?viewModelScope, so everything cancels when the screen goes away.
Part 3 of 5

Detailed answer

The design decisions, the complete Kotlin solution, and a walk through it one block at a time.

3.1Design decisions

Settle these before writing code; each one shows up in the solution.

collectLatest is the whole trick

A new query cancels the block still running for the old one, whether it is waiting, searching or about to publish.

delay() is the debounce

The block sleeps first; typing again cancels the sleep, so only a pause reaches the network.

One immutable UI state

SearchUi in a StateFlow: the screen renders results, a spinner or an error from a single value.

3.2Solution

Complete, compiling Kotlin with coroutines, built with warnings as errors and covered by tests/mobile/MobileTests.kt. The Java and TypeScript tabs do the same job with each language's own tools: Java compiled and run in our tests, TypeScript run in our tests.

SearchViewModel.ktKotlin
1import kotlin.coroutines.cancellation.CancellationException2import kotlin.time.Duration3import kotlin.time.Duration.Companion.milliseconds4import kotlinx.coroutines.CoroutineScope5import kotlinx.coroutines.currentCoroutineContext6import kotlinx.coroutines.delay7import kotlinx.coroutines.ensureActive8import kotlinx.coroutines.flow.MutableStateFlow9import kotlinx.coroutines.flow.StateFlow10import kotlinx.coroutines.flow.asStateFlow11import kotlinx.coroutines.flow.collectLatest12import kotlinx.coroutines.flow.distinctUntilChanged13import kotlinx.coroutines.flow.map14import kotlinx.coroutines.flow.update15import kotlinx.coroutines.launch16 17data class SearchUi(val results: List<String> = emptyList(), val loading: Boolean = false, val error: String? = null)18 19/**20 * Search-as-you-type: debounce keystrokes, cancel stale requests, never show21 * results for a query the user has already changed. In an Android ViewModel, pass viewModelScope.22 */23class SearchViewModel(24  scope: CoroutineScope,25  private val debounce: Duration = 300.milliseconds,26  private val minLength: Int = 2,27  private val search: suspend (String) -> List<String>,28) {29  private val query = MutableStateFlow("")30  private val _ui = MutableStateFlow(SearchUi())31  val ui: StateFlow<SearchUi> = _ui.asStateFlow()32 33  fun onQueryChanged(text: String) {34    query.value = text35  }36 37  init {38    scope.launch {39      query.map { it.trim() }.distinctUntilChanged().collectLatest { q ->   // a new keystroke cancels this block40        if (q.length < minLength) {41          _ui.value = SearchUi()42          return@collectLatest43        }44        delay(debounce)                                // the debounce: cancelled if typing continues45        _ui.update { it.copy(loading = true) }46        try {47          val found = search(q)48          currentCoroutineContext().ensureActive()     // the query changed while we waited: drop it49          _ui.value = SearchUi(results = found)50        } catch (e: CancellationException) {51          throw e                                      // the newer query owns the UI state52        } catch (e: Exception) {53          _ui.value = SearchUi(error = "Search failed. Pull to retry.")54        }55      }56    }57  }58}
58 linesUTF-8Kotlin

3.3Line-by-line walkthrough

The same code in the order you would explain it in the room. The line numbers follow the Kotlin file; the Java and TypeScript tabs above have the same steps in the same order.

1

Latest keystroke wins

Trim, skip repeats, and collectLatest: each new query cancels the previous block.

SearchViewModel.ktKotlin
39      query.map { it.trim() }.distinctUntilChanged().collectLatest { q ->   // a new keystroke cancels this block
lines 39–39UTF-8Kotlin
2

Ignore tiny queries

Under two characters: clear results and stop. No request.

SearchViewModel.ktKotlin
40        if (q.length < minLength) {41          _ui.value = SearchUi()42          return@collectLatest43        }
lines 40–43UTF-8Kotlin
3

The debounce

delay throws CancellationException if another keystroke arrives first, so only pauses trigger a search.

SearchViewModel.ktKotlin
44        delay(debounce)                                // the debounce: cancelled if typing continues
lines 44–44UTF-8Kotlin
4

Search with a spinner

Keep the old results visible while loading; the injected search function makes the network call.

SearchViewModel.ktKotlin
45        _ui.update { it.copy(loading = true) }46        try {47          val found = search(q)
lines 45–47UTF-8Kotlin
5

Drop stale responses

ensureActive() throws if the query changed while the search ran, even if the search itself ignored cancellation.

SearchViewModel.ktKotlin
48          currentCoroutineContext().ensureActive()     // the query changed while we waited: drop it49          _ui.value = SearchUi(results = found)
lines 48–49UTF-8Kotlin
6

Cancellation is not an error

Rethrow CancellationException so the newer query owns the UI; real failures show a message.

SearchViewModel.ktKotlin
50        } catch (e: CancellationException) {51          throw e                                      // the newer query owns the UI state52        } catch (e: Exception) {53          _ui.value = SearchUi(error = "Search failed. Pull to retry.")54        }
lines 50–54UTF-8Kotlin

Complexity: At most one request per debounce window

Part 4 of 5

Q&A

The questions interviewers ask after the code works. Answer out loud, then open.

4.1Follow-up questions

How would you test timing?
Inject a short debounce and a recording search function; type four keystrokes quickly and assert one call. That test ships with this code. With kotlinx-coroutines-test, use virtual time instead.
Why not debounce() + mapLatest()?
That works too. collectLatest with delay keeps the short-query rule, the debounce and the stale-response guard in one readable block.
Part 5 of 5

Extra depth

The cases that break naive solutions, how the same design looks on iOS, and what to practise next.

5.1Edge cases

Say these before the interviewer does.

Show detailsHide details
  • Typing, then deleting back to one character
  • Network error, then typing again
  • Screen closed mid-request (viewModelScope cancels it)
  • Identical consecutive queries (distinctUntilChanged skips them)

5.2On iOS

The same design in Swift and Apple's frameworks.

Show detailsHide details
ApproachSwift / iOS
Combine$query.debounce(for: .milliseconds(300), scheduler: RunLoop.main).removeDuplicates() then switchToLatest over the search publisher.
async/awaitCancel the previous Task on each keystroke; Task.sleep(for:) is the debounce and Task.checkCancellation() drops stale results.
AI Engineer · Search-as-you-type with debounce and cancellation