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.
Wait until the user pauses typing before acting. Typing 'kotlin' sends one request, not six.
When the query changes, the work for the old query stops, so no network or CPU is spent on results nobody will see.
Responses can arrive out of order. A slow answer for 'kot' must never replace the answer for 'kotlin'.
A StateFlow holds the current screen state and notifies the UI when it changes. One immutable SearchUi object keeps results, spinner and error consistent.
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.
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 ask | Interviewer 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. |
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.
A new query cancels the block still running for the old one, whether it is waiting, searching or about to publish.
The block sleeps first; typing again cancels the sleep, so only a pause reaches the network.
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.
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}1import java.time.Duration;2import java.util.List;3import java.util.concurrent.CopyOnWriteArrayList;4import java.util.concurrent.Executors;5import java.util.concurrent.ScheduledExecutorService;6import java.util.concurrent.ScheduledFuture;7import java.util.concurrent.TimeUnit;8import java.util.concurrent.atomic.AtomicInteger;9import java.util.function.Consumer;10import java.util.function.Function;11 12/**13 * Search-as-you-type: debounce keystrokes, ignore stale requests, never show14 * results for a query the user has already changed. Listeners run on a background thread:15 * on Android, post to the main thread (for example with a Handler or LiveData.postValue).16 */17public final class SearchViewModel implements AutoCloseable {18 public record SearchUi(List<String> results, boolean loading, String error) {19 static SearchUi empty() { return new SearchUi(List.of(), false, null); }20 }21 22 private final Function<String, List<String>> search;23 private final Duration debounce;24 private final int minLength;25 private final ScheduledExecutorService timer = Executors.newScheduledThreadPool(2, r -> {26 Thread t = new Thread(r, "search");27 t.setDaemon(true);28 return t;29 });30 private final List<Consumer<SearchUi>> listeners = new CopyOnWriteArrayList<>();31 private final AtomicInteger generation = new AtomicInteger(); // bumps on every new query32 private volatile SearchUi ui = SearchUi.empty();33 private ScheduledFuture<?> pending;34 private String lastQuery = "";35 36 public SearchViewModel(Function<String, List<String>> search, Duration debounce, int minLength) {37 this.search = search;38 this.debounce = debounce;39 this.minLength = minLength;40 }41 42 public SearchUi ui() { return ui; }43 44 public void subscribe(Consumer<SearchUi> listener) { listeners.add(listener); }45 46 public synchronized void onQueryChanged(String text) {47 String q = text.trim();48 if (q.equals(lastQuery)) return; // distinctUntilChanged49 lastQuery = q;50 int mine = generation.incrementAndGet();51 if (pending != null) pending.cancel(false); // the debounce: typing again restarts the wait52 if (q.length() < minLength) {53 set(SearchUi.empty());54 return;55 }56 pending = timer.schedule(() -> run(q, mine), debounce.toMillis(), TimeUnit.MILLISECONDS);57 }58 59 private void run(String q, int mine) {60 set(new SearchUi(ui.results(), true, null));61 try {62 List<String> found = search.apply(q);63 if (mine != generation.get()) return; // the query changed while we waited: drop it64 set(new SearchUi(found, false, null));65 } catch (RuntimeException e) {66 if (mine == generation.get()) set(new SearchUi(List.of(), false, "Search failed. Pull to retry."));67 }68 }69 70 private void set(SearchUi next) {71 ui = next;72 for (Consumer<SearchUi> l : listeners) l.accept(next);73 }74 75 @Override76 public void close() { timer.shutdownNow(); }77}1export interface SearchUi {2 results: string[];3 loading: boolean;4 error: string | null;5}6 7export interface SearchOptions {8 debounceMs?: number;9 minLength?: number;10}11 12/**13 * Search-as-you-type: debounce keystrokes, ignore stale requests, never show14 * results for a query the user has already changed. In React, call subscribe from an effect.15 */16export class SearchViewModel {17 ui: SearchUi = { results: [], loading: false, error: null };18 private search: (q: string) => Promise<string[]>;19 private debounceMs: number;20 private minLength: number;21 private listeners = new Set<(ui: SearchUi) => void>();22 private timer: ReturnType<typeof setTimeout> | undefined;23 private lastQuery = "";24 private generation = 0; // bumps on every new query25 26 constructor(search: (q: string) => Promise<string[]>, options: SearchOptions = {}) {27 this.search = search;28 this.debounceMs = options.debounceMs ?? 300;29 this.minLength = options.minLength ?? 2;30 }31 32 subscribe(listener: (ui: SearchUi) => void): () => void {33 this.listeners.add(listener);34 return () => this.listeners.delete(listener);35 }36 37 onQueryChanged(text: string): void {38 const q = text.trim();39 if (q === this.lastQuery) return; // distinctUntilChanged40 this.lastQuery = q;41 const mine = ++this.generation;42 clearTimeout(this.timer); // the debounce: typing again restarts the wait43 if (q.length < this.minLength) {44 this.set({ results: [], loading: false, error: null });45 return;46 }47 this.timer = setTimeout(() => void this.run(q, mine), this.debounceMs);48 }49 50 private async run(q: string, mine: number): Promise<void> {51 this.set({ ...this.ui, loading: true });52 try {53 const found = await this.search(q);54 if (mine !== this.generation) return; // the query changed while we waited: drop it55 this.set({ results: found, loading: false, error: null });56 } catch {57 if (mine === this.generation) this.set({ results: [], loading: false, error: "Search failed. Pull to retry." });58 }59 }60 61 private set(ui: SearchUi): void {62 this.ui = ui;63 this.listeners.forEach((l) => l(ui));64 }65}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.
Latest keystroke wins
Trim, skip repeats, and collectLatest: each new query cancels the previous block.
39 query.map { it.trim() }.distinctUntilChanged().collectLatest { q -> // a new keystroke cancels this blockIgnore tiny queries
Under two characters: clear results and stop. No request.
40 if (q.length < minLength) {41 _ui.value = SearchUi()42 return@collectLatest43 }The debounce
delay throws CancellationException if another keystroke arrives first, so only pauses trigger a search.
44 delay(debounce) // the debounce: cancelled if typing continuesSearch with a spinner
Keep the old results visible while loading; the injected search function makes the network call.
45 _ui.update { it.copy(loading = true) }46 try {47 val found = search(q)Drop stale responses
ensureActive() throws if the query changed while the search ran, even if the search itself ignored cancellation.
48 currentCoroutineContext().ensureActive() // the query changed while we waited: drop it49 _ui.value = SearchUi(results = found)Cancellation is not an error
Rethrow CancellationException so the newer query owns the UI; real failures show a message.
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 }Complexity: At most one request per debounce window
Q&A
The questions interviewers ask after the code works. Answer out loud, then open.
4.1Follow-up questions
How would you test timing?
Why not debounce() + mapLatest()?
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
| Approach | Swift / iOS |
|---|---|
| Combine | $query.debounce(for: .milliseconds(300), scheduler: RunLoop.main).removeDuplicates() then switchToLatest over the search publisher. |
| async/await | Cancel the previous Task on each keystroke; Task.sleep(for:) is the debounce and Task.checkCancellation() drops stale results. |