Open search in any serious messenger and you get four behaviors at once: a counter (“3 of 12”), up/down arrows that walk through hits, every matched word highlighted, and the list jumping to the current hit. Each one looks trivial. Together they produce a notorious pile of state: the query, the match list, the current index, an “is searching” flag, maybe a Job for the running search. These live in a ViewModel, a composable, and a couple of click listeners, and the bugs hide in the gaps between them: two quick taps on the arrow, a rotation mid-search, a keystroke landing while the previous search is still running.
This post builds the whole feature around one MutableSharedFlow and one rarely used operator: scan (the Flow sibling of the collections' runningFold). No locks, no mutable fields, and the reducer is testable without an emulator.
The design in one picture
Every interaction becomes a single emit into a shared flow. scan folds those events into a SearchState, feeding the previous result back in as the accumulator. A small mapping function turns that state into what Compose actually draws.
The property that makes this robust: scan runs its lambda inside the collecting coroutine, one event at a time. A second event cannot enter the reducer until the first has returned, so two taps never interleave halfway through an update. That guarantee comes from how the operator is built, not from anything you have to remember to do.
Step 1: Name every event and every state
data class Message(val id: Long, val text: String)
/** A hit inside message [messageIndex]; [endExclusive] follows Kotlin range conventions. */
data class Match(
val messageId: Long, // stable identity, survives list changes
val messageIndex: Int,
val start: Int,
val endExclusive: Int,
)
sealed interface SearchEvent {
data class Query(val text: String) : SearchEvent
data object Next : SearchEvent // toward newer messages
data object Prev : SearchEvent // toward older messages
data object Cancel : SearchEvent
data object Refresh : SearchEvent // the message list changed under an open search
}
sealed interface SearchState {
data object Initial : SearchState
data class Found(
val query: String,
val matches: List<Match>, // reading order, oldest first
val current: Int, // index into matches
) : SearchState
data class NoMatch(val query: String) : SearchState
}
Two deliberate choices:
-
Foundstores positions, not text. The message list stays the single source of truth; the search result is only a set of coordinates into it. - Because both hierarchies are sealed, adding another event later turns every
whenthat forgets it into a compile error instead of a silent no-op.
Step 2: Write the reducer as a plain function
The reducer is (state, event, messages) -> state. No coroutines, no Android.
internal fun reduce(
state: SearchState,
event: SearchEvent,
messages: List<Message>,
): SearchState = when (event) {
is SearchEvent.Query -> when {
event.text.isBlank() -> SearchState.Initial
state.activeQuery == event.text -> state // idempotent; data changes arrive as Refresh
else -> search(messages, event.text)
}
SearchEvent.Next -> state.stepped(+1)
SearchEvent.Prev -> state.stepped(-1)
SearchEvent.Cancel -> SearchState.Initial
SearchEvent.Refresh -> when (state) {
SearchState.Initial -> state
is SearchState.Found -> refresh(messages, state.query, previous = state.matches[state.current])
is SearchState.NoMatch -> search(messages, state.query)
}
}
private val SearchState.activeQuery: String?
get() = when (this) {
is SearchState.Found -> query
is SearchState.NoMatch -> query
SearchState.Initial -> null
}
private fun search(messages: List<Message>, query: String): SearchState {
val matches = findMatches(messages, query)
return if (matches.isEmpty()) SearchState.NoMatch(query)
else SearchState.Found(query, matches, current = matches.lastIndex) // newest first, like a chat
}
/** Re-run the search after the data changed, keeping the user on the same hit if it still exists. */
private fun refresh(messages: List<Message>, query: String, previous: Match): SearchState {
val matches = findMatches(messages, query)
if (matches.isEmpty()) return SearchState.NoMatch(query)
val kept = matches.indexOfFirst { it.messageId == previous.messageId && it.start == previous.start }
return SearchState.Found(query, matches, current = if (kept >= 0) kept else matches.lastIndex)
}
private fun SearchState.stepped(delta: Int): SearchState =
if (this is SearchState.Found) {
copy(current = (current + delta).mod(matches.size)) // wraps in both directions
} else this // arrows do nothing without hits
internal fun findMatches(messages: List<Message>, query: String): List<Match> = buildList {
messages.forEachIndexed { index, message ->
var from = 0
while (true) {
val hit = message.text.indexOf(query, from, ignoreCase = true)
if (hit < 0) break
add(Match(message.id, index, hit, hit + query.length))
from = hit + query.length // non-overlapping hits
}
}
}
Int.mod returns a non-negative result, so (0 - 1).mod(5) is 4. Plain % would give -1 and crash on the first "Prev" from the oldest hit.
Two events deserve a note. Query is idempotent: re-sending the text the state already holds changes nothing, which keeps the user's position after a rotation. The price is that an unchanged query would never notice new or edited messages, so data changes get their own event. Refresh re-runs the search and re-selects the previous hit by messageId and start (list positions shift when messages arrive, ids do not). That is why Match carries the id.
Step 3: Fold the events with scan
class ChatSearchViewModel(messageSource: MessageSource) : ViewModel() {
val messages: StateFlow<List<Message>> = messageSource.observe()
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())
private val events = MutableSharedFlow<SearchEvent>(
extraBufferCapacity = 64,
onBufferOverflow = BufferOverflow.DROP_OLDEST,
)
val uiState: StateFlow<SearchUiState> = merge(
events,
messages.drop(1).map { SearchEvent.Refresh }, // data changed under an open search
)
.scan<SearchEvent, SearchState>(SearchState.Initial) { state, event ->
val snapshot = messages.value
if (event.isHeavy) withContext(Dispatchers.Default) { reduceSafely(state, event, snapshot) }
else reduceSafely(state, event, snapshot) // O(1) navigation stays on the collector
}
.map(SearchState::toUi)
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), SearchUiState())
private val SearchEvent.isHeavy: Boolean
get() = this is SearchEvent.Query || this == SearchEvent.Refresh
fun onEvent(event: SearchEvent) {
events.tryEmit(event)
}
private fun reduceSafely(state: SearchState, event: SearchEvent, snapshot: List<Message>) =
try {
reduce(state, event, snapshot)
} catch (e: Exception) {
Log.e("ChatSearch", "reducer failed for $event", e)
state // keep the pipeline alive
}
}
Several details here earn their keep:
-
Explicit type arguments on
scan. Writingscan(SearchState.Initial) { ... }makes Kotlin infer the accumulator type asSearchState.Initial, and the lambda then refuses to returnFound. Spell out<SearchEvent, SearchState>. -
Only the heavy events hop to
Default. Scanning text (Query,Refresh) is O(total text) and belongs off the main thread;Next,PrevandCancelare O(1) and run directly. Either way the collecting coroutine suspends until the reducer returns, so the next event waits in the buffer and ordering is preserved. -
WhileSubscribed(5_000), notEagerly. The pipeline survives a rotation but stops five seconds after the last collector leaves, instead of running for the ViewModel's whole life. The consequence, covered under failure modes, is thatscanstarts over fromInitialwhen the UI returns after a long absence. -
mergeties the message stream to the search. CollectinguiStatealso collectsmessages, so while the screen is visible every data change produces aRefresh.drop(1)skips only the replayed current value. If the pipeline restarts after the five-second window,scanrestarts fromInitialtoo, and theQueryre-sent by the search bar reads the then-current list, so no change is missed. -
messages.valueis read once per event.Listis a read-only interface, not an immutable one, so this is a stable snapshot only if the source emits lists it never mutates afterwards (emit copies, or use an immutable collection). Note the semantics:Refreshcarries no payload and means "re-run against the newest list", so a burst of updates simply recomputes on the latest one. The cost is a possible one-frame gap between the list Compose is drawing and the list the last reduction saw; thecoerceInguard inMessageBubblekeeps that frame from crashing, though a highlight on a just-shortened message visibly clamps to the end of its text until the next reduction lands. If you need strict consistency, pass the list inside the events instead (Query(text, messages),Refresh(messages)) at the price of threading it through the UI. -
tryEmit, notemit. UI callbacks are not suspending, and withDROP_OLDESTa full buffer discards the oldest event instead of rejecting the new one, sotryEmitreturnstrue.
Step 4: Map the state to what Compose draws
Compose should not know what Found means. Give it a flat, display-ready model:
data class Highlight(val start: Int, val end: Int, val isCurrent: Boolean)
data class Focus(val query: String, val ordinal: Int, val messageIndex: Int)
data class SearchUiState(
val counter: String = "",
val navigationEnabled: Boolean = false,
val showNoResults: Boolean = false,
val highlights: Map<Int, List<Highlight>> = emptyMap(), // keyed by message index
val focus: Focus? = null,
)
fun SearchState.toUi(): SearchUiState = when (this) {
SearchState.Initial -> SearchUiState()
is SearchState.NoMatch -> SearchUiState(showNoResults = true)
is SearchState.Found -> SearchUiState(
counter = "${matches.size - current} of ${matches.size}", // newest hit is "1"
navigationEnabled = matches.size > 1,
highlights = matches.withIndex().groupBy(
keySelector = { it.value.messageIndex },
valueTransform = { (i, m) -> Highlight(m.start, m.endExclusive, isCurrent = i == current) },
),
focus = Focus(query, current, matches[current].messageIndex),
)
}
Focus exists for one reason: it is a stable key for the scroll effect. It changes exactly when the user lands on a different hit, and not when something unrelated recomposes.
Step 5: Scroll and highlight in Compose
@OptIn(FlowPreview::class)
@Composable
fun ChatSearchBar(ui: SearchUiState, onEvent: (SearchEvent) -> Unit, onClose: () -> Unit) {
var text by rememberSaveable { mutableStateOf("") }
val latestOnEvent by rememberUpdatedState(onEvent)
val lifecycleOwner = LocalLifecycleOwner.current
LaunchedEffect(lifecycleOwner) {
lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { // re-sends the query on every restart
latestOnEvent(SearchEvent.Query(text)) // restore at once, no blank window
snapshotFlow { text }
.drop(1) // that value was just sent
.debounce(150) // then one Query per pause, not per keystroke
.collect { latestOnEvent(SearchEvent.Query(it)) }
}
}
Row(verticalAlignment = Alignment.CenterVertically) {
TextField(
value = text,
onValueChange = { text = it },
isError = ui.showNoResults,
singleLine = true,
modifier = Modifier.weight(1f),
)
Text(ui.counter, modifier = Modifier.padding(horizontal = 8.dp))
IconButton(onClick = { onEvent(SearchEvent.Prev) }, enabled = ui.navigationEnabled) {
Icon(Icons.Default.KeyboardArrowUp, contentDescription = "Older match")
}
IconButton(onClick = { onEvent(SearchEvent.Next) }, enabled = ui.navigationEnabled) {
Icon(Icons.Default.KeyboardArrowDown, contentDescription = "Newer match")
}
IconButton(onClick = { text = ""; onEvent(SearchEvent.Cancel); onClose() }) {
Icon(Icons.Default.Close, contentDescription = "Close search")
}
}
}
@Composable
fun ChatList(messages: List<Message>, ui: SearchUiState) {
val listState = rememberLazyListState()
LaunchedEffect(ui.focus) {
val target = ui.focus?.messageIndex ?: return@LaunchedEffect
val offset = -listState.layoutInfo.viewportSize.height / 3 // land in the upper third
val distance = abs(listState.firstVisibleItemIndex - target)
if (distance > 40) listState.scrollToItem(target, offset)
else listState.animateScrollToItem(target, offset)
}
LazyColumn(state = listState) {
itemsIndexed(messages, key = { _, m -> m.id }) { index, message ->
MessageBubble(message.text, ui.highlights[index].orEmpty())
}
}
}
private val OtherMatch = Color(0xFFFFE08A)
private val CurrentMatch = Color(0xFFFF9F43)
@Composable
fun MessageBubble(text: String, highlights: List<Highlight>) {
val styled = remember(text, highlights) {
buildAnnotatedString {
append(text)
for (h in highlights) {
val start = h.start.coerceIn(0, text.length)
val end = h.end.coerceIn(start, text.length)
addStyle(
SpanStyle(background = if (h.isCurrent) CurrentMatch else OtherMatch),
start, end,
)
}
}
}
Text(styled, modifier = Modifier.padding(12.dp))
}
Matches store UTF-16 offsets, which is exactly what AnnotatedString consumes, so there is no conversion layer to get wrong.
Testing without an emulator
Because the reducer is a pure function, a test is just a fold:
class ChatSearchReducerTest {
private val messages = listOf(
Message(1, "hello"),
Message(2, "world"),
Message(3, "Hello again"),
)
@Test
fun `prev and next wrap around the two hits`() = runTest {
val states = flowOf(
SearchEvent.Query("hello"), SearchEvent.Prev, SearchEvent.Prev, SearchEvent.Next,
).scan<SearchEvent, SearchState>(SearchState.Initial) { s, e -> reduce(s, e, messages) }
.toList()
val positions = states.filterIsInstance<SearchState.Found>().map { it.current }
assertEquals(listOf(1, 0, 1, 0), positions)
}
@Test
fun `unknown word lands in NoMatch and arrows are inert`() {
val none = reduce(SearchState.Initial, SearchEvent.Query("zzz"), messages)
assertEquals(SearchState.NoMatch("zzz"), none)
assertEquals(none, reduce(none, SearchEvent.Next, messages))
}
}
Real-world failure modes
The table covers the quick lookups. These deserve a longer explanation:
Events are lost before anyone collects. A MutableSharedFlow with replay = 0 has nowhere to keep a value when there is no collector, so it is discarded, and tryEmit still returns true, because the no-collector path never fails. The visible failure is a different one: with a busy collector and a zero-sized buffer, tryEmit returns false. The extra buffer fixes that second case; only collecting first fixes the first. For taps this rarely matters, since the screen emits after it subscribes. For events from outside the UI (a deep link, a notification action), route them through a Channel and receiveAsFlow(), which holds them until something collects.
The five-second window resets the search. With WhileSubscribed(5_000) the scan stops five seconds after the app leaves the screen and restarts from Initial when it returns, while the text field still shows the restored query. Collecting the text inside repeatOnLifecycle(STARTED) fixes this: every restart re-reads the field and re-sends a Query. That first emission deliberately bypasses the debounce; otherwise the results would stay blank for 150 ms after every return from the background, and only later keystrokes are debounced. Within the window (a rotation) the state already holds that query, so the idempotent branch leaves the position alone; after a long absence the search re-runs and lands on the newest hit. Eagerly would avoid the reset, at the cost of keeping the match list and the collector alive while nobody is looking.
Data changes under an open search. New messages shift list positions, and an edited message can invalidate stored offsets. The Refresh event, merged in from messages, re-runs the search and keeps the user on the same hit by id. The coerceIn calls in MessageBubble are a last line of defense against a one-frame race: they guarantee no crash, not correct highlights, so for that frame a span on a shortened message visibly clamps to the end of the text. Refresh is the actual fix.
Case folding corrupts offsets. The tempting text.lowercase().indexOf(query.lowercase()) is wrong for some alphabets: lowercasing can change string length (the Turkish dotted capital İ is the classic example), so offsets computed on the folded copy no longer point into the original text and highlights drift. indexOf(ignoreCase = true) on the original string keeps offsets honest.
Long jumps feel broken. animateScrollToItem across thousands of items either takes long or stutters while measuring. The distance check in ChatList snaps for far targets and animates only the final stretch. If your list uses reverseLayout = true for chat-style bottom anchoring, remember that item index 0 is the newest message; translate with messages.lastIndex - messageIndex before scrolling.
One exception can end the feature. If the reducer throws, the collecting coroutine fails and uiState stops updating, with no visible error. Catching inside the reducer and returning the previous state keeps the pipeline alive; logging keeps the bug visible.
Where this pattern stops fitting
-
Server-side or paged search. If matches are not all in memory, the reducer needs a suspending data source and cancellation of superseded queries. Move to
flatMapLatestfor theQuerybranch and keepscanfor navigation. -
Very large local histories. Scanning every message per keystroke is O(n). Past tens of thousands of messages, push the work into an FTS index in the database and treat its result as the
matcheslist. -
State that must survive process death.
scanholds state in memory. Persist the query (and optionally the current ordinal) and replay aQueryon restore.
🔚 Takeaways
- Model interactions as a sealed event type and results as a sealed state type; the compiler then polices completeness.
-
scangives you a reducer with the serialization guarantee built in: one event at a time, in the collector's coroutine. - Keep the reducer a pure function; side effects (scrolling, focus) belong in effects keyed on a stable value derived from state.
- Most real bugs live at the edges: dropped emissions, replayed queries, index math. Test the reducer directly and design the edges deliberately.
📱 Crack Your Next Android Interview
If you’re targeting a senior Android role at a FAANG or top-tier MNC, syntax knowledge alone won’t get you through the loop. I highly recommend “Cracking Top MNC Android Interviews” — a senior-level playbook covering framework internals, Jetpack Compose, coroutines, Android-specific system design, and DSA reframed around real mobile constraints, to help you walk into bar-raiser rounds ready.
- E-book: Available on Google Play
- Kindle Edition: Available on Amazon
- Topmate: Available on Topmate
- Also available in Paperback & Hardcover.
Originally published on Medium.





Top comments (0)