Search and Filter
Personal Catalogue: Android (Kotlin & Compose)
Course 1 ยท Chapter 8 ยท Search, Tag Filter and "Do I Own This?"
This is the chapter that delivers the app's reason for existing. You are standing in a shop holding a paperback; you type three letters of its title; the phone tells you "You already have 1 match" or
"Not in your catalogue", and in the second case one tap starts adding it with the title already filled in. Along the way you will move filtering from memory into the database, add a tag filter, and meet
two Kotlin flow operators, debounce and flatMapLatest, that make live search behave.
debounce, flatMapLatest) is confirmed only by the
official Flow reference and by forum discussions, which I treated as illustration rather than authority. The SQLite side (LIKE and ESCAPE) is confirmed from SQLite's own
documentation. Room's handling of nullable query parameters and of the SQL inside @Query was not found in any source, so the DAO query is the likeliest place for a build error; Room
checks the SQL when you build, so the message will name the problem.
Where the Filtering Happens
Chapter 4 filtered in memory: load every item, then discard the ones that do not match the selected type. That is fine for one condition, but search plus type plus tag would mean ever more Kotlin code that re-implements what a database does well. Now the filtering moves into one SQL query, and the view model just passes the user's choices to it.
| Choice | In memory (Chapter 4) | In the database (this chapter) |
|---|---|---|
| Cost as the collection grows | Reads every item on every change | Returns only the matches |
| Adding another filter | More filter { } lines | One more AND clause |
| Where the rules live | View model | DAO query (testable in Chapter 10) |
| Web catalogue equivalent | Filtering a fetched array in JavaScript | Item.objects.filter(Q(title__icontains=q) | Q(creator__icontains=q)) |
Step 1: The Search Query
One DAO method takes three optional conditions: a text pattern, a type id and a tag id. A condition that is empty ('' or NULL) is switched off by the
:param IS NULL OR ... idiom, so a single query serves every combination. Add it to ItemDao:
Read the three conditions as a sentence: the type matches (or no type was chosen), and the title or creator matches the pattern (or no pattern was typed), and the item carries the tag (or no tag was
chosen). The tag test uses a subquery on the link table from Chapter 2, which is why that table has its own index on tagId. Each LIKE ends with ESCAPE '\', explained
next. The count query lets the screen tell "your catalogue is empty" from "nothing matches" without loading everything.
The pattern, and why ESCAPE matters
SQLite's documentation says LIKE treats % as "any run of characters" and _ as "any one character", and that the ESCAPE clause names a single character that, placed
before %, _ or itself, makes it literal. Without that, someone searching for the title "100% Pure" would have the % read as a wildcard. SQLite also documents that
LIKE ignores case only for ASCII letters: "dune" matches "Dune", but "รฉ" does not match "ร". For a catalogue with a few accented titles that is a real, small limit, and Exercise 2's
notes mention a fix. Put the pattern builder in data/Search.kt:
Order matters: the escape character must be escaped first, or the backslashes added for % and _ would themselves be doubled. In the repository add:
Step 2: A Search That Waits for You to Stop Typing
A query on every keystroke is wasteful and makes the list flicker, so wait until the user pauses. debounce(250) does that: per the Flow reference, it drops a value if a
newer one arrives within the timeout, and the latest value is always emitted. The second operator is flatMapLatest: it turns each set of filters into a database Flow
and, when the filters change, cancels the old one and switches to the new. Without it, a slow earlier query could finish after a faster later one and overwrite the newer results.
Two details. The text box must show what is typed immediately, so the view model keeps the raw text in one flow and debounces a separate copy for searching. And chip taps should not be delayed, so only the text is debounced.
Step 3: State and ViewModel
ListUiState gains the query, the tag list and the selected tag; ListViewModel is rewritten around three input flows. This replaces the version from Chapter 4 (and its in-memory filtering)
completely.
Note that distinctUntilChanged() stops a repeat query when the debounced text settles on a value the filters already hold. The @OptIn line acknowledges that
debounce and flatMapLatest are marked as preview or experimental in the coroutines library; check which annotations your version asks for. Also, the removed "TEMPORARY" sample code
from Chapter 6 is gone for good here.
Step 4: Passing the Title to the Form
The "Add" button in the not-found state must open the form with the searched text as the title. Give the route an optional starting title and use it in the form view model:
In the NavHost the list destination changes its add callback to take the title:
onAddClick = { title -> navController.navigate(FormRoute(initialTitle = title)) }. The edit load in FormViewModel overwrites the title with the stored one, so
initialTitle only affects a new item, as intended.
Step 5: The Screen
ListScreen now passes onQueryChange, onTagSelected and onClearFilters from the view model, and onAddClick becomes
(String) -> Unit. Replace ListContent with the version below; TypeFilterRow and ItemRow from Chapter 4 stay as they are, and a second filter row
is added for tags. Remember to update the preview or call sites for the new parameters.
The when in NoResults is the "do I own this?" logic, in order: no items at all; nothing under the chip filters (the answer is not "you don't own it", it is "not within these
filters", so offer to clear them); otherwise the search text found nothing, which really does mean it is not in the catalogue, so offer to add it. That distinction is why the chip filters and the text query are
tracked separately. Add Icons.Filled.Search and the other imports the IDE asks for.
Try It
Add a few items with different types and tags. Type part of a title: matching items appear after a short pause and the heading says how many you own. Type something you do not have: "Not in your catalogue" appears
with an Add button; tap it and the form opens with the text as the title. Select a tag chip, then a type chip, and see them combine; tap the tag chip again to turn it off. Finally search for 100% and
a_b to check that the escaping does not treat % and _ as wildcards.
.searchable modifier and a #Predicate in the @Query do the same job, and SwiftData rebuilds the query
as the search text changes. The "do I own this?" answer and the add-with-title shortcut are the same design. The debounce and flatMapLatest plumbing mostly disappears there because SwiftUI re-runs the
query itself.
Challenges
Make all the changes and run the app. With at least six items (two of them tagged "sci-fi", one a CD), record what appears for each of: the search "dun"; the search "xyz"; the tag "sci-fi" alone; the tag "sci-fi" plus the type CD; and "xyz" with the tag "sci-fi" selected. Say which message each case shows and why they differ.
๐ View solutionExtend the search so it also matches the notes field. Say what you changed, whether the result is still sensible for a "do I own this?" check, and describe one way to make the search
case-insensitive for accented letters (such as ร and รฉ) despite the ASCII-only behaviour of LIKE.
Explain, with a concrete example of timings, what could go wrong if the view model used map and collected each query's flow separately instead of
flatMapLatest. Then say what the user would see if likePattern did not escape % and they searched for "100%".
Chapter 8 Quick Reference
- One query, three optional conditions:
(:x IS NULL OR col = :x); text:(:pattern = '' OR title LIKE :pattern ESCAPE '\' OR creator LIKE :pattern ESCAPE '\') - Tag filter:
id IN (SELECT itemId FROM item_tag WHERE tagId = :tagId) LIKE:%any run,_any one; case-insensitive for ASCII only; escape\first, then%and_query.debounce(250)waits for a pause;flatMapLatest { repository.search(...) }cancels the previous query- Keep the displayed text and the searched (debounced) text as separate flows
- Empty-result logic: no items → "empty catalogue"; chip filter active → "clear filters"; text only → "Not in your catalogue" + Add with the title
FormRoute(itemId, initialTitle)pre-fills the form for a new item
Flow reference, that debounce drops values followed by newer ones within the timeout and always emits the
latest, and that flatMapLatest maps each value to a flow and switches to the newest; from SQLite's documentation, that LIKE uses % and _, is case-insensitive for
ASCII only, and that ESCAPE takes a single (ASCII) character that makes the next %, _ or itself literal.Not checked, from general knowledge: that Room accepts nullable query parameters and the
:param IS NULL OR idiom; that a backslash inside a Kotlin raw string reaches SQLite
unchanged; that Room's compile-time SQL check accepts ESCAPE '\'; the exact opt-in annotations for debounce and flatMapLatest in your coroutines version; the
combine overloads with a constructor reference; Icons.Filled.Search; and all code, none of which was compiled. The forum threads in the search results were informal and I did not
treat them as sources.