Android Engineering

Practice Kotlin, Flow, coroutine cancellation, DataStore, Room, Compose, RecyclerView, permissions, and layout through realistic questions and worked code answers.

~2 hr 56 min reading~2 hr practice estimate
Suggest content

Android Code and Architecture Questionnaire

🟪 Language syntax · 🟦 Types/APIs · 🟩 Correct pattern · 🟥 Bug · 🟨 Gotcha · 🧠 Explanation

An independent, self-authored interview bank for Android engineers and Mobile Tech Leads. Attempt the prompts before opening the answer key. Explain ownership, execution order, cancellation, lifecycle, and a test that could disprove your answer; naming an API alone is insufficient.

Assumptions: Kotlin on Android/JVM with Jetpack Compose, AndroidX Lifecycle, and kotlinx.coroutines. Code is illustrative, with imports, dependency setup, and app-specific types omitted unless shown; it has not been compiled as an Android project. Room examples describe transaction semantics without prescribing a Room major version. Pin dependencies and check the matching APIs when implementing them. Official references were checked on 22 October 2026; questions are not official assessment material.

Practice suggestion: Select six prompts for a 45–60 minute discussion, including two code reviews and one lifecycle or delivery scenario. This is a suggested practice duration, separate from the calculated reading estimate.

Extended practice (AND-25–40): Official Android/Kotlin references for these additions were checked on 24 October 2026. Their answer blocks include imports and explicit application contracts. AND-25–29 were compiled with Kotlin/JVM 2.3.10 and the bundled coroutine library; they were not executed. The DataStore, Room, test-library, Compose, and RecyclerView examples are illustrative and have not been built as an Android application. Use the stated dependencies and verify them in your project's pinned toolchain.

Related lessons: Mobile systems and leadership, Mobile Tech Lead and architecture, architecture and SOLID, and backend and distributed systems. Use these for shared architectural concepts; Android-specific answers live here.

Questions

For IDE workflows and measurement, continue with the Android Studio debugging and profiling questionnaire: build errors, Logcat, breakpoints, CPU/GPU and memory tools, and choosing evidence before changing code.

AND-01 — Can a private setter protect a mutable list?

The cart checks product IDs in its add method, but an outside caller can access the same mutable list.

KOTLIN
class Cart {
    var productIds: MutableList<String> = mutableListOf()
        private set
​
    fun add(id: String) {
        require(id.isNotBlank())
        productIds.add(id)
    }
}
​
val cart = Cart()
cart.productIds.add("")
cart.productIds.clear()
Optional follow-up questions
  • How would you expose the cart contents without exposing the mutable collection?
  • How do a read-only reference, a read-only collection interface, and an immutable object differ?

AND-02 — Which function implementation runs for each call?

The same formatter object is used through different declared types. Follow how each call chooses a function.

KOTLIN
open class Formatter {
    open fun format(value: String): String = "base:$value"
    fun format(value: Int): String = "number:$value"
}
​
class MoneyFormatter : Formatter() {
    override fun format(value: String): String = "money:$value"
}
​
fun Formatter.debugName(): String = "formatter"
fun MoneyFormatter.debugName(): String = "money"
​
val formatter: Formatter = MoneyFormatter()
println(formatter.format("10"))
println(formatter.format(10))
println(formatter.debugName())
Optional follow-up questions
  • What would make debugName dispatch through an overridable member?
  • When would composing separate behaviors be clearer than adding subclasses?

AND-03 — Can a read-only computed property still crash or change its result?

The display label is calculated from a mutable, nullable name each time it is read.

KOTLIN
class Profile {
    var displayName: String? = null
​
    val initials: String
        get() = displayName!!.trim().split(" ")
            .filter { it.isNotEmpty() }
            .joinToString("") { it.first().uppercase() }
}
Optional follow-up questions
  • How would you handle a missing name explicitly?
  • Would caching with lazy still return the intended result after the name changes?

AND-04 — How can a screen state model prevent contradictory states?

A screen currently combines an isLoading flag, a nullable error, and nullable items. The product also wants to refresh already visible content.

KOTLIN
data class SearchScreenState(
    val isLoading: Boolean,
    val error: String?,
    val items: List<String>?
)
Optional follow-up questions
  • How would a sealed state hierarchy and an exhaustive renderer express the valid combinations?
  • Where would you represent a recoverable refresh error while content remains visible?

AND-05 — Why can a listener keep an Activity alive after the screen closes?

Events lives for the whole process and retains each registered listener. The Activity registers a listener that captures its instance.

KOTLIN
class CheckoutActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Events.add { title = "Checkout updated" }
    }
}
Optional follow-up questions
  • Which lifecycle boundary matches the period when this listener is needed?
  • How does a reachable-object leak under garbage collection differ from a Swift ARC retain cycle?

AND-06 — Does marking a function suspend move blocking work off the main thread?

A ViewModel calls load from viewModelScope. The implementation performs blocking work.

KOTLIN
class ReportRepository {
    suspend fun load(): String {
        Thread.sleep(2_000)
        return "ready"
    }
}
Optional follow-up questions
  • Where should the dispatcher boundary live so UI callers can use the API safely?
  • How does the choice differ for a genuinely asynchronous HTTP client and for CPU-heavy work?

AND-07 — How should a dashboard load own its child coroutines?

This dashboard loads a required account and optional recommendations using requests started in GlobalScope.

KOTLIN
suspend fun loadDashboard(api: DashboardApi): Dashboard {
    val account = GlobalScope.async { api.account() }
    val recommendations = GlobalScope.async { api.recommendations() }
    return Dashboard(account.await(), recommendations.await())
}
Optional follow-up questions
  • How would you express an all-or-nothing policy with structured concurrency?
  • How would supervision and explicit error handling support optional recommendations?

AND-08 — How should a retry function handle coroutine cancellation?

The user leaves the screen while refresh is running. Its broad exception handler treats every failure as a reason to retry.

KOTLIN
suspend fun refresh(repository: FeedRepository): List<Article> {
    return try {
        repository.fetch()
    } catch (error: Exception) {
        delay(500)
        repository.fetch()
    }
}
Optional follow-up questions
  • Which failures are actually safe to retry, and who owns cleanup?
  • Why do runCatching and NonCancellable need a deliberate policy rather than blanket use?

AND-09 — Can this StateFlow increment lose updates?

Two coroutines can call increment on different threads while sharing this count.

KOTLIN
private val count = MutableStateFlow(0)
​
fun increment() {
    count.value = count.value + 1
}
Optional follow-up questions
  • Why must a payment request or once-only analytics event stay outside the update calculation?
  • How would you keep several related state fields consistent?

AND-10 — Can an older search result replace a newer one on the main thread?

The user searches for ca, then cat. Both calls and all result changes use the main dispatcher, but the older request finishes last.

KOTLIN
class SearchViewModel(private val repository: SearchRepository) : ViewModel() {
    val result = MutableStateFlow<List<String>>(emptyList())
​
    fun search(query: String) {
        viewModelScope.launch {
            result.value = repository.search(query)
        }
    }
}
Optional follow-up questions
  • How would a generation check protect publication if cancellation arrives too late?
  • How would a fake repository reproduce the completion order without timing sleeps?

AND-11 — Should a cache hold a Mutex while waiting for a network request?

Every cache access uses this same Mutex. A refresh keeps it locked while the network request is suspended.

KOTLIN
private val mutex = Mutex()
private var cached: Catalog? = null
​
suspend fun refresh(api: CatalogApi) {
    mutex.withLock {
        cached = api.load()
    }
}
Optional follow-up questions
  • How would you prevent a response started before invalidation from overwriting newer cache state?
  • What cancellation and non-reentrant locking risks remain?

AND-12 — Does SharedFlow guarantee that an important UI event is delivered once?

The payment event is emitted while the screen has stopped collecting in the background.

KOTLIN
private val events = MutableSharedFlow<String>(replay = 0)
​
suspend fun paymentCompleted() {
    events.emit("Payment confirmed")
}
Optional follow-up questions
  • How do replay and extra buffer capacity behave when no collector exists?
  • How would you handle a disposable snackbar differently from an important payment outcome?

AND-13 — Why does the second StateFlow collector never start?

A Fragment tries to collect two StateFlows sequentially inside repeatOnLifecycle. Neither flow normally completes.

KOTLIN
viewLifecycleOwner.lifecycleScope.launch {
    viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
        viewModel.profile.collect { renderProfile(it) }
        viewModel.notifications.collect { renderNotifications(it) }
    }
}
Optional follow-up questions
  • What happens when the view stops, starts again, or is destroyed?
  • How should a Compose screen collect UI state without launching a collector on every recomposition?

AND-14 — Why does changing this list fail to update Compose reliably?

Tapping Add tag changes the remembered list in place, but the displayed text does not update reliably.

KOTLIN
@Composable
fun TagEditor() {
    val tags = remember { mutableListOf("Android") }
    Column {
        Button(onClick = { tags.add("Kotlin") }) { Text("Add tag") }
        Text(tags.joinToString())
    }
}
Optional follow-up questions
  • How would you implement an immutable replacement or a snapshot state list?
  • Which user-visible performance measurements matter beyond recomposition counts?

AND-15 — Who should own the state and validation of a Compose form?

A settings form needs text input, a switch, one selected option, a dropdown, saving, and validation feedback.

Optional follow-up questions
  • What would a reusable stateless control accept and emit?
  • Which small UI values need saveable state, and which decisions belong to a ViewModel or domain layer?

AND-16 — Why can a remembered checkbox move to the wrong list item?

Rows can reorder and new rows can appear at the top. Each row currently remembers its own checkbox state without an explicit item key.

KOTLIN
@Composable
fun TaskList(tasks: List<Task>) {
    LazyColumn {
        items(tasks) { task ->
            var checked by remember { mutableStateOf(false) }
            Row {
                Checkbox(checked = checked, onCheckedChange = { checked = it })
                Text(task.title)
            }
        }
    }
}
Optional follow-up questions
  • Which domain identifier is a safe key, and why are titles or newly generated UUIDs unsuitable?
  • What should survive item removal, screen recreation, or process death?

AND-17 — When should an account-loading Compose effect restart?

The same screen instance can receive a new account ID and callback, but its loading effect uses a constant key.

KOTLIN
@Composable
fun AccountScreen(accountId: String, onLoaded: (String) -> Unit) {
    LaunchedEffect(Unit) {
        val name = accountRepository.loadName(accountId)
        onLoaded(name)
    }
}
Optional follow-up questions
  • How do LaunchedEffect keys and rememberUpdatedState solve different parts of the problem?
  • Who should own an operation that must continue after the screen leaves composition?

AND-18 — Which screen data should survive recreation and process death?

A checkout screen holds a query, selected item ID, fetched catalog, pending order, and authentication token.

Optional follow-up questions
  • Which owner and storage mechanism fits each value?
  • How does saved-state restoration differ from a force-stop or a fresh launch?

AND-19 — What information should cross an order-navigation boundary?

Users can reach an order detail or confirmation screen from the app or from an external deep link.

Optional follow-up questions
  • Who should own the back stack and navigation callbacks?
  • How do session changes, server authorization, and duplicate submission affect the flow?

AND-20 — What makes an icon-only action accessible?

The delete action has no accessible name. The same screen also contains a custom painted chart.

KOTLIN
Icon(
    imageVector = Icons.Default.Delete,
    contentDescription = null,
    modifier = Modifier.clickable { deleteDraft() }
)
Optional follow-up questions
  • How would you correct the action with a semantic component and a localized label?
  • What text alternative, reading order, focus behavior, and large-text checks does the chart and screen need?

AND-21 — How should an offline app store a local edit safely?

Users must see their notes immediately and be able to edit them while offline. The device later synchronizes those edits with the server.

Optional follow-up questions
  • What belongs in the local transaction, and what belongs in the synchronization worker?
  • How would you represent an edit conflict and a pending operation that has an unknown server result?

AND-22 — Can WorkManager prevent an upload from creating a duplicate server change?

The server accepts an upload mutation, then the worker dies before saving the acknowledgement on the device.

Optional follow-up questions
  • Which failures should be retried, and which constraints should control the worker?
  • What do unique work and scheduled timing actually guarantee?

AND-23 — Does Android Keystore make the app a trusted payment authority?

A proposed banking app embeds a shared API secret, logs tokens, and treats a successful biometric prompt as permission for any payment.

Optional follow-up questions
  • Which risks do Keystore, transport protection, cache cleanup, and safe telemetry each address?
  • Where should user authorization and payment validation be enforced?

AND-24 — How can you prove that a stale-result fix works?

A search screen sometimes displays stale data and occasionally submits the same action twice. The team needs evidence before expanding a fix.

Optional follow-up questions
  • Which UI, persistence, retry, and real-parallelism cases need separate tests?
  • How would Android, iOS, and backend owners share the behavior contract and rollout criteria?

AND-25 — How should a Flow adapter release a callback listener?

A Bluetooth battery monitor sends repeated updates and returns a subscription handle. Either of two screens may start or stop collecting at any time.

Optional follow-up questions
  • How would you handle callback errors and a callback racing with cancellation?
  • Should each collector own a separate subscription or share an explicitly managed upstream source?

AND-26 — How can a callback adapter accept only one terminal result?

A legacy API may call back synchronously, finish after cancellation, or call a terminal callback twice.

Optional follow-up questions
  • How would you handle cancellation before the request handle becomes available?
  • Which controlled callback orderings would prove that completion and cleanup happen safely?

AND-27 — Why can copying a StateFlow value fail to notify collectors?

A cart owner mutates the list inside the current state, then copies the outer state object while reusing that same list.

Optional follow-up questions
  • How would you expose read-only state and replace nested values safely?
  • Why is StateFlow a current-state holder rather than a record of every intermediate change?

AND-28 — How do you choose a Flow policy when updates arrive too quickly?

A dashboard receives audit records, live progress updates, and requests for expensive previews. A slow collector cannot treat all three streams the same way.

Optional follow-up questions
  • Which stream fits buffering, conflation, or collectLatest?
  • How would CPU-heavy preview work notice cancellation without blocking the UI?

AND-29 — How can you limit concurrent requests while keeping result order?

A comparison screen loads up to 100 selected products, with at most four requests active and results returned in selection order.

Optional follow-up questions
  • How would timeout and failure policy affect the whole batch?
  • When would a bounded worker queue be better than creating one child coroutine per input?

AND-30 — Where should a DataStore increment read the old value?

Two screens increment one persisted counter. Each currently reads the counter first and writes the calculated replacement in a later edit.

Optional follow-up questions
  • How would you declare the application-scoped DataStore and expose an observable read?
  • Why would blocking the main thread or creating separate instances fail to repair the transaction boundary?

AND-31 — How can a Room query read an order and its lines consistently?

An order summary reads an order row and its line rows while a refresh replaces both sets of data.

Optional follow-up questions
  • How would the entities, relation, DAO, and database declaration express that contract?
  • Why can combining two independent flows still show an inconsistent order summary?

AND-32 — How can a debounce test avoid real-time sleeps?

A typeahead flow waits briefly after typing before searching. A later debounced query should cancel the previous request.

Optional follow-up questions
  • What work runs when time reaches the exact debounce boundary?
  • How would the design change if every keystroke must cancel the previous request immediately?

AND-33 — How can a restored draft stay attached to the correct document?

A note editor restores a custom draft while the same destination can now display a different document.

Optional follow-up questions
  • What should a bounded custom saver accept or reject?
  • Which draft data belongs in durable storage instead of the saved-state bundle?

AND-34 — Who should remove a listener registered by a composable?

A screen observes its lifecycle owner. Recomposition can change the callback, and navigation can replace the owner.

Optional follow-up questions
  • Which value should restart registration and which should update without restarting it?
  • Why does a lifecycle callback not prove that the user saw the screen exactly once?

AND-35 — When does derivedStateOf help a scrolling Compose screen?

A long results list shows a Back to first result button only after the first item leaves the top.

Optional follow-up questions
  • How do a plain expression, remember, and derivedStateOf differ for this threshold?
  • Which frame timings and affected composition scopes would show whether the extra state calculation helps?

AND-36 — How should a button start a suspending snackbar action?

A help button starts a suspending snackbar action. The user may tap again or navigate away before it finishes.

Optional follow-up questions
  • When would changing-key work belong in LaunchedEffect instead?
  • Who should own a business operation that must survive leaving the screen?

AND-37 — How should the app handle a denied camera permission?

A receipt screen supports camera scanning and manual entry. Scanning should request permission only after the user chooses that feature.

Optional follow-up questions
  • How would the manifest declaration, rationale, cancel path, and activity-result callback fit together?
  • How would you handle permission changes while keeping manual entry usable?

AND-38 — Why can ListAdapter miss a row that was edited in place?

A RecyclerView adapter receives the same mutable list after an existing row title is changed in place.

Optional follow-up questions
  • How would item identity and content comparison differ in a ListAdapter?
  • Which tests cover reordered rows and rapid consecutive edits without using captured adapter positions?

AND-39 — Why can an unconstrained LazyColumn fail inside a scrolling Column?

A vertically scrolling Column contains an unconstrained LazyColumn for transaction rows.

Optional follow-up questions
  • How would you put the header, transactions, and footer in one scrolling container?
  • When is a separate bounded list or a scroller on another axis appropriate?

AND-40 — How should a Scaffold screen apply its content padding?

An edge-to-edge inbox hides rows behind its top bar when padding is ignored, but shows excess gaps when several layers add the same system-bar space.

Optional follow-up questions
  • How would you express one inset owner in the Scaffold and LazyColumn?
  • Which navigation modes, cutouts, and large-text cases need device checks?

Answer key

AND-01 — Answer

Short answer: No. A private setter stops callers replacing the list, but it does not stop them changing the list itself. Keep the mutable data private and expose controlled operations so every change goes through validation.

Detailed explanation:

🟥 The setter only prevents replacing the list reference. Callers still mutate the list and bypass validation. Keep the mutable collection private and expose a snapshot or deliberately immutable model.

KOTLIN
class Cart {
    private val ids = mutableListOf<String>()
    val productIds: List<String>
        get() = ids.toList()
​
    fun add(id: String) {
        require(id.isNotBlank())
        ids.add(id)
    }
}

🧠 val prevents reassignment through that binding; List removes mutation operations from its interface. Neither makes mutable elements deeply immutable. This snapshot isolates the String collection from the private list; it does not make concurrent access safe. For frequently observed UI state, publish immutable snapshots through a read-only state contract with one mutation owner. Copy cost is a tradeoff. Kotlin properties.

AND-02 — Answer

Short answer: The compiler chooses an overload from the declared argument type. The string member then uses the runtime object's override, but extension functions use the receiver's declared type. These rules produce money:10, number:10, and formatter.

Detailed explanation:

Illustrative correction when dynamic naming is required: make it part of the member contract rather than an extension.

KOTLIN
interface FormatterIdentity {
    fun debugName(): String
}
class MoneyIdentity : FormatterIdentity {
    override fun debugName(): String = "money"
}
val identity: FormatterIdentity = MoneyIdentity()
check(identity.debugName() == "money")

The output is money:10, number:10, then formatter. The call's argument types select a format overload; the selected open string member dispatches to the runtime receiver's override. Extensions are resolved using the receiver's declared type and do not add virtual members. Declare an open/interface member for dynamic dispatch. Kotlin classes and members are final unless opened or abstracted. Kotlin inheritance, Kotlin extensions.

MechanismDecisionUseful boundary
OverloadingSelect a compatible signature at compile timeConvenient variants of one operation
OverridingRuntime implementation of an overridable memberSubstitutable behavior behind a contract
ExtensionResolve a callable from declared types and scopeLocal convenience without owning the type

🟨 Prefer composition when behaviors vary independently or inheritance would expose invalid operations. A subtype must preserve the contract; changing a payment method into a silent no-op violates substitutability even when it compiles.

AND-03 — Answer

Short answer: Yes. The getter can crash when the name is missing, and it builds the label again on every read. A Kotlin val prevents assigning the property itself; a custom getter can still return different values when the data it reads changes.

Detailed explanation:

🟥 !! crashes for an absent name. Each read recomputes, allocates, and reflects the current mutable name. A lazy initializer normally caches its first result, so it would become stale after a name change.

KOTLIN
class Profile {
    var displayName: String? = null
​
    val initials: String
        get() = displayName.orEmpty()
            .trim()
            .split(Regex("\\s+"))
            .filter { it.isNotEmpty() }
            .take(2)
            .joinToString("") { it.first().uppercase() }
}

This is an illustrative display rule, not a complete international name/grapheme algorithm. A getter is suitable for cheap derivation; expensive transformation should have an explicit cache invalidation strategy or be prepared when inputs change. Validate nullable transport input at a boundary rather than scattering assertions. Java platform types can still undermine null-safety assumptions. Kotlin properties, null safety.

AND-04 — Answer

Short answer: Represent each valid screen condition with a distinct state, such as loading, content, or failure. This makes invalid combinations harder to create than several independent flags. If refreshing content is allowed, represent that combination deliberately instead of accidentally forbidding it.

Detailed explanation:

🟩 A closed state model makes an initial exclusive-state contract explicit:

KOTLIN
sealed interface SearchUiState {
    data object Loading : SearchUiState
    data class Content(val items: List<String>) : SearchUiState
    data class Failure(val message: String) : SearchUiState
}
​
fun description(state: SearchUiState): String = when (state) {
    SearchUiState.Loading -> "Loading"
    is SearchUiState.Content -> "${state.items.size} results"
    is SearchUiState.Failure -> state.message
}

The model deliberately excludes simultaneous content/loading/error. If stale content must remain visible during refresh, let Content carry a refresh status and recoverable message, or use orthogonal states whose combinations are valid by construction. An empty successful list differs from failure. An exhaustive when helps surface new variants; avoid a catch-all else that silently hides them. Kotlin sealed hierarchies.

AND-05 — Answer

Short answer: A long-lived event source can keep its listener, and that listener can keep the Activity it captures. Garbage collection cannot reclaim an object that is still reachable this way. Remove the same listener instance when its intended screen lifetime ends.

Detailed explanation:

Illustrative visible-lifetime subscription; the same callback instance is registered and removed. Events is the application dependency from the prompt.

KOTLIN
class CheckoutActivity : ComponentActivity() {
    private val listener: () -> Unit = { title = "Checkout updated" }
    override fun onStart() {
        super.onStart()
        Events.add(listener)
    }
    override fun onStop() {
        Events.remove(listener)
        super.onStop()
    }
}

🟥 Process root → Events → listener closure → Activity keeps the Activity reachable after it should be released. Store the same listener instance and unregister at the matching lifecycle boundary; use onStart/onStop if observation is only needed while visible, or onCreate/onDestroy for that lifetime. Fragment listeners that access its view should follow the view lifecycle. A lifecycle-aware flow can make cancellation ownership clearer.

🧠 Android's ART tracing garbage collector can reclaim an unreachable reference cycle. Swift ARC cannot reclaim an otherwise isolated strong cycle without breaking an ownership edge. Both still leak logically when a longer-lived owner retains an obsolete screen. A weak reference can change semantics and does not replace listener management. Files, sockets, cursors, and subscriptions need deterministic cleanup, such as use or finally; GC timing is not a cleanup contract. Android memory management, Swift ARC comparison.

AND-06 — Answer

Short answer: No. Suspend allows a function to pause without blocking when it uses a suspending operation; it does not choose a background thread. Blocking calls still block the thread running them, so the implementation must move those calls to an appropriate dispatcher.

Detailed explanation:

🟥 suspend permits suspension; it does not dispatch a function to a background thread. Thread.sleep blocks whichever thread executes it.

KOTLIN
class ReportRepository(private val ioDispatcher: CoroutineDispatcher) {
    suspend fun load(): String = withContext(ioDispatcher) {
        blockingReportRead()
    }
}

Use an injected IO dispatcher for unavoidable blocking IO, with an appropriate cancellation/close strategy; moving blocking work does not automatically make it interruptible. Use delay for a simulated asynchronous wait. A main-safe asynchronous HTTP API does not require wrapping every call in IO. Move substantial CPU work to an appropriate default dispatcher and measure it. The repository should provide main-safe operations so UI callers need not know its implementation. Android coroutine best practices.

AND-07 — Answer

Short answer: The dashboard load should own its requests so cancellation and failure follow the lifetime of the caller. Structured child coroutines provide that relationship; GlobalScope does not. If one result is optional, handle that expected failure explicitly instead of assuming supervision turns failure into success.

Detailed explanation:

🟥 GlobalScope work is detached from the caller's lifetime. Cancelling the caller does not establish ownership of those requests. For all-or-nothing results:

KOTLIN
suspend fun loadDashboard(api: DashboardApi): Dashboard = coroutineScope {
    val account = async { api.account() }
    val recommendations = async { api.recommendations() }
    Dashboard(account.await(), recommendations.await())
}

A child failure cancels this normal scope and its sibling work; the caller receives the failure. For optional recommendations, use supervisorScope, handle the optional async result's expected failure at await, and rethrow cancellation. A required-account failure must still fail the overall operation. Supervision isolates child failure propagation; it neither consumes exceptions nor invents fallback values. CoroutineExceptionHandler observes otherwise unhandled exceptions; it is not a retry or recovery mechanism. Kotlin coroutine exception handling, coroutineScope.

AND-08 — Answer

Short answer: Cancellation means the caller no longer wants the work, not that the network failed. Rethrow cancellation and retry only selected recoverable failures. A later cancellable suspension may stop this example anyway, but catching cancellation as an ordinary error still gives the function the wrong contract.

Detailed explanation:

🟥 The broad catch intercepts cancellation as if it were a transient fetch failure. delay normally throws again when already cancelled, so this exact example need not perform a second request; the bug is the incorrect cancellation/error contract, which breaks more easily with changed cleanup or non-cooperative operations. CancellationException contract.

KOTLIN
suspend fun refresh(repository: FeedRepository): List<Article> {
    return try {
        repository.fetch()
    } catch (cancelled: CancellationException) {
        throw cancelled
    } catch (failure: IOException) {
        delay(500)
        repository.fetch()
    }
}

This demonstrates one bounded retry, not a complete production policy. Retry only eligible failures and idempotent operations; honor server throttling. Put resource release in finally/use. runCatching also catches cancellation unless deliberately rethrown. Reserve NonCancellable for narrowly bounded cleanup that genuinely must suspend; wrapping a whole request defeats ownership. CPU loops need cooperative checks such as ensureActive. NonCancellable cleanup guidance, ensureActive.

AND-09 — Answer

Short answer: Yes. Reading the current count and writing the next count are two separate operations, so concurrent callers can overwrite each other. Use an atomic state update to calculate the replacement from the latest value. Keep that calculation free of effects because it may run more than once.

Detailed explanation:

🟥 Two callers can read 0 and each write 1. StateFlow provides thread-safe individual operations; the read-modify-write expression is not one atomic operation. This is a lost-update race, without requiring an unsafe implementation inside StateFlow.

KOTLIN
fun increment() {
    count.update { current -> current + 1 }
}

🟨 The update function may be evaluated multiple times under contention. Keep it pure: no network requests, logging that must occur once, or independently mutated external state. For a multi-field invariant, publish a single immutable state and atomically derive its replacement, or use a consistently applied mutex/owner. Atomics do not make a later HTTP effect transactional. MutableStateFlow.update.

AND-10 — Answer

Short answer: Yes. The main thread prevents simultaneous state access, but requests can still finish in a different order from when they started. Cancel obsolete work and check the request generation before publishing, so only the result for the current user intent becomes visible.

Detailed explanation:

🧠 Main confinement prevents simultaneous memory access, not stale responses across suspension. Use a generation that identifies user intent, cancel obsolete work, and revalidate before publishing.

KOTLIN
private var generation = 0L
private var searchJob: Job? = null
private val result = MutableStateFlow<List<String>>(emptyList())
​
fun search(query: String) {
    val requestGeneration = ++generation
    searchJob?.cancel()
    searchJob = viewModelScope.launch {
        try {
            val items = repository.search(query)
            ensureActive()
            if (requestGeneration == generation) result.value = items
        } catch (cancelled: CancellationException) {
            throw cancelled
        } catch (failure: IOException) {
            if (requestGeneration == generation) {
                reportSearchFailure(failure)
            }
        }
    }
}

This member fragment assumes all request/generation access is on main and reportSearchFailure does not suspend. Expose an asStateFlow() view to consumers. The identity check remains useful where cancellation cannot prevent an old callback/result. A query flow with latest-only transformation is another option, with an explicit cancellation contract at the repository boundary. Test with controlled completions: hold ca, finish cat, then finish ca; only cat may be visible. Duplicate query text alone is not always a unique request identity. Kotlin shared-state guidance.

AND-11 — Answer

Short answer: A coroutine can wait while holding a Mutex, but every other caller using that lock must also wait. Usually fetch outside the lock, then briefly lock to check that the response is still current before storing it. Holding the lock throughout can be intentional when the operation truly must be serialized.

Detailed explanation:

🟨 Suspension while owning a coroutine mutex is possible; withLock is inline. Waiters suspend rather than blocking a thread, but the lock is still unavailable during the request. Long ownership can delay unrelated operations; reacquiring the same non-reentrant mutex can deadlock. withLock releases on exit, including an exception.

KOTLIN
private val mutex = Mutex()
private var generation = 0L
private var cached: Catalog? = null
​
suspend fun invalidate() = mutex.withLock {
    generation += 1
    cached = null
}
​
suspend fun refresh(api: CatalogApi) {
    val requestGeneration = mutex.withLock { ++generation }
    val response = api.load()
    currentCoroutineContext().ensureActive()
    mutex.withLock {
        if (generation == requestGeneration) cached = response
    }
}

Every cache/generation access must follow this boundary. This policy makes the latest started refresh/invalidation win; a failed newer refresh may leave older data unpublished. Choose that policy deliberately. Single-flight coordination can share one in-flight result without locking unrelated state for the full request. Deliberate serialization can be appropriate when the entire operation must be exclusive, with bounded execution and no recursive acquisition. Local locking cannot enforce a server's distributed invariant. Kotlin mutex and shared state, Mutex API.

Android/Kotlin deadlocks: follow the dependency that cannot progress

The original question holds a lock across a request, which can cause contention without a deadlock; the corrected refresh above moves that request outside the lock. A deadlock requires a closed dependency: each participant needs progress that another participant cannot make while the wait remains in place. A coroutine can suspend and free its thread while remaining part of that cycle. “No thread is blocked” therefore does not prove the operation can finish.

The five families below use the same wait-graph principle as GCD deadlocks. They are illustrative Kotlin/JVM Android examples, not an exhaustive taxonomy. The broken variants were not executed and should not be run in a production app or an ordinary UI test process. Imports and app dependencies are omitted where indicated; no compilation or runtime verification is claimed. Official references were checked on 22 October 2026.

Family 1: a coroutine reacquires its own non-reentrant Mutex

🟥 Broken: the public replace method owns mutex, then calls another public method that tries to acquire that same mutex.

KOTLIN
class SearchCache {
    private val mutex = Mutex()
    private var rows: List<String> = emptyList()
​
    suspend fun replace(newRows: List<String>): Int = mutex.withLock {
        rows = newRows.toList()
        size()
    }
​
    suspend fun size(): Int = mutex.withLock { rows.size }
}

Who waits, and why: replace → size's acquisition → mutex release → replace returning. The inner acquisition cannot succeed until the outer acquisition releases, but the outer body cannot finish until the inner call returns. This is a self-cycle. Coroutine Mutex is non-reentrant; JVM synchronized monitors are reentrant for their owning thread. That difference does not make a monitor an interchangeable coroutine lock: a monitor can block a thread and does not establish coroutine ownership across suspension. Mutex semantics, JVM monitor reentrancy.

🟩 Corrected: acquire once at each public boundary and call a private non-acquiring helper while the lock is held.

KOTLIN
class SearchCache {
    private val mutex = Mutex()
    private var rows: List<String> = emptyList()
​
    suspend fun replace(newRows: List<String>): Int = mutex.withLock {
        rows = newRows.toList()
        sizeLocked()
    }
​
    suspend fun size(): Int = mutex.withLock { sizeLocked() }
​
    private fun sizeLocked(): Int = rows.size
}

sizeLocked has a private precondition: its callers already own the mutex. Keep all access behind that boundary. Do not “fix” the cycle by launching the mutation elsewhere without defining when replace returns and what state it guarantees.

Owner-token gotcha: a non-null debugging owner token does not enable recursive locking. Reacquiring with the same token identity throws IllegalStateException instead of suspending. Use a token for a logical acquisition attempt; a shared constant token across independent contenders can report misuse rather than queueing them normally. Mutex.lock owner checks.

Verify: exercise replacement followed by size, concurrent callers, and cancellation while waiting. Assert the expected count and that a later caller can acquire the mutex. A bounded test watchdog detects a failure to finish; the watchdog is not the repair.

Family 2: two Mutexes acquired in opposite orders

🟥 Broken: assume these members belong to one cache/metadata owner. Two coroutines can each acquire one lock before trying the other.

KOTLIN
private val cacheMutex = Mutex()
private val metadataMutex = Mutex()
private var cacheVersion = 0L
private var recordedVersion = 0L
​
suspend fun publishVersion(version: Long) = cacheMutex.withLock {
    metadataMutex.withLock {
        cacheVersion = version
        recordedVersion = version
    }
}
​
suspend fun resetVersions() = metadataMutex.withLock {
    cacheMutex.withLock {
        cacheVersion = 0L
        recordedVersion = 0L
    }
}

Who waits, and why: if A owns cacheMutex and B owns metadataMutex, A waits for B's metadata lock while B waits for A's cache lock. Neither can reach its release. A sequential run can finish, so “it passed once” does not disprove the possible interleaving.

🟩 Corrected: make one helper enforce the fixed global order, cacheMutex → metadataMutex, and route both operations through it.

KOTLIN
private suspend fun <T> withCacheAndMetadata(action: () -> T): T =
    cacheMutex.withLock {
        metadataMutex.withLock { action() }
    }
​
suspend fun publishVersion(version: Long) = withCacheAndMetadata {
    cacheVersion = version
    recordedVersion = version
}
​
suspend fun resetVersions() = withCacheAndMetadata {
    cacheVersion = 0L
    recordedVersion = 0L
}

Every method that needs both resources must use the same order, including callbacks and maintenance paths. For a dynamic set of resource locks, define a stable, unique total order over canonical resource identities and deduplicate repeated resources before acquisition; do not order by an unstable display name or inconsistent hash. If the two fields always form one invariant, one mutex may be simpler than two. Nested withLock also releases an already-held outer lock when waiting for the inner acquisition is cancelled. Safe acquisition/release guidance.

Verify: an isolated broken-code demonstration can gate each path immediately after its first acquisition to establish the cycle. For the corrected code, coordinate callers before acquisition instead; a barrier inside the first critical section waiting for a second owner would introduce a new deadlock into the test. Assert both operations finish and cacheVersion == recordedVersion through a correctly synchronized snapshot. Use a documented global lock-order audit alongside the test.

Family 3: runBlocking occupies the Android UI thread needed by its child

🟥 Broken: this callback runs on the actual Android main thread. Dispatchers.Main below posts work to that thread's Looper; it is deliberately not Main.immediate.

KOTLIN
fun onRefreshTapped() {
    runBlocking {
        withContext(Dispatchers.Main) {
            render(repository.load())
        }
    }
}

Who waits, and why: the main thread is blocked until runBlocking finishes; its child needs the main Looper to run; the Looper cannot process that work until the callback returns. The blocking builder's coroutine event loop is not a general Android Looper pump. A different dispatcher or an immediately executable inner operation changes the particular schedule, so do not claim every syntactic use of runBlocking deadlocks. Blocking an Android UI callback is still the wrong lifetime/execution contract. runBlocking blocks its calling thread.

🟩 Corrected: let the UI emit an intent to a ViewModel-owned coroutine; its main-safe repository suspends rather than making the UI callback wait synchronously. Illustrative members inside a ViewModel; repository, rows, and errorMessage are app-owned dependencies/state.

KOTLIN
fun onRefreshRequested() {
    viewModelScope.launch {
        try {
            val snapshot = repository.load()
            ensureActive()
            rows.value = snapshot
        } catch (cancelled: CancellationException) {
            throw cancelled
        } catch (failure: IOException) {
            errorMessage.value = "Refresh unavailable"
        }
    }
}

The repository moves any actual blocking IO to its appropriate injected dispatcher, as discussed in AND-06. Overlapping refreshes also need the AND-10 freshness policy. Moving just the inner body to IO while keeping runBlocking on main still blocks the caller and can recreate the cycle when that body later needs main. Android main-safe repository guidance.

Verify: use a controllable repository to hold a request, confirm the callback returns and another main-thread interaction can run, then complete/cancel it and assert publication behavior. Investigate real freezes with main/worker stacks and a system trace. A blocked main thread can have low CPU; an ANR report alone does not prove this particular cycle. Do not depend on an in-process UI timeout to recover a deliberately blocked main Looper. Android ANR diagnosis.

Family 4: a rendezvous-channel protocol waits for code it cannot reach

🟥 Broken: the only coroutine must finish send before reaching its own receive. With the default suspend-overflow policy, this channel has no buffer.

KOTLIN
suspend fun firstRefreshStatus(): String {
    val statuses = Channel<String>(Channel.RENDEZVOUS)
    try {
        statuses.send("ready")
        return statuses.receive()
    } finally {
        statuses.cancel()
    }
}

Who waits, and why: send → matching receive → continuation after send. The receiver cannot be reached because this same coroutine is suspended at the send. This is a protocol self-dependency, even though its thread is free. A different case—waiting for an external sender that never reports a result—may be a missing-completion bug without a circular wait; diagnose the producer's actual owner. Rendezvous-channel send/receive contract.

🟩 Corrected: when independent producer/consumer work really is needed, give them structured lifetimes so each can make progress. Here one producer owns normal close, and the surrounding operation cancels the channel on exit.

KOTLIN
suspend fun firstRefreshStatus(): String = coroutineScope {
    val statuses = Channel<String>(Channel.RENDEZVOUS)
    val producer = launch {
        try {
            statuses.send("ready")
        } finally {
            statuses.close()
        }
    }
    try {
        val first = statuses.receive()
        producer.join()
        first
    } finally {
        statuses.cancel()
    }
}

For one immediately available value with no independent producer, simply return that value; a channel adds needless protocol complexity. Adding capacity can make this one-send example finish, but cannot generally fix a pipeline whose producer fills the buffer before allowing its consumer to start. Choose capacity, backpressure, close/error propagation, and undelivered-resource cleanup from the real contract. Channel closing and structured producer/consumer ownership.

Verify: run the corrected producer/consumer on a single test dispatcher to prove it does not require parallel threads, verify the received value, and cancel while send/receive is suspended. Check producer completion and failure propagation. A test that only adds a large buffer can hide the original dependency rather than validate the protocol.

Family 5: Deferred results form a circular task dependency

🟥 Broken: lazy creation ensures both references are initialized before either task starts; it does not make their result dependencies valid.

KOTLIN
suspend fun cyclicSummary(): String = coroutineScope {
    lateinit var profile: Deferred<String>
    lateinit var summary: Deferred<String>
    profile = async(start = CoroutineStart.LAZY) {
        "profile:${summary.await()}"
    }
    summary = async(start = CoroutineStart.LAZY) {
        "summary:${profile.await()}"
    }
    profile.start()
    summary.start()
    summary.await()
}

Who waits, and why: profile needs summary's result, and summary needs profile's result. Both tasks suspend; more threads cannot create either missing prerequisite. Unlike a long HTTP wait, neither task has a path to producing a base result within this graph. Deferred.await is nonblocking and cancellable, which permits cancellation of the operation but does not remove its circular business dependency. Deferred.await semantics.

🟩 Corrected: orient dependencies as an acyclic graph. Fetch independent inputs concurrently; compute the summary after the profile exists. DashboardApi, Dashboard, and summarize are illustrative app types/functions.

KOTLIN
suspend fun loadDashboard(api: DashboardApi): Dashboard = coroutineScope {
    val profileTask = async { api.profile() }
    val preferencesTask = async { api.preferences() }
    val profile = profileTask.await()
    val preferences = preferencesTask.await()
    Dashboard(profile, preferences, summarize(profile))
}

One input no longer awaits its own derived output. Normal structured failure/cancellation propagates to sibling work; an optional-input fallback would need an explicit different failure policy. Do not replace await with join: joining the same cyclic tasks still waits for completion. Structured async behavior.

Verify: draw the task graph before coding, then use fake inputs with independently released completions in both orders. Assert the summary uses the accepted profile snapshot and that cancellation/failure leaves no unowned worker. A bounded watchdog is useful for regression containment, not proof that every possible dependency graph is acyclic.

Distinguish liveness failures before selecting a repair

ObservationWhat to establishProportionate response
Closed lock/task/dispatcher wait cycleEvery dependency needed to break the cycle is waiting inside itRemove an edge: one acquisition boundary, common lock order, async UI boundary, or acyclic protocol
Long critical sectionThe owner still has an independent path to finishReduce protected work, move IO out, snapshot/revalidate, or deliberately serialize with a documented bound
Starvation / saturated workersWork is repeatedly postponed or no worker is available for the needed continuationBound admission, remove blocking worker waits, and inspect scheduling; more threads alone is not a proof
Missing completionA callback/result/producer has no terminal signal or ownerSpecify success/error/cancellation paths and ensure every owned operation terminates or is cancelled
LivelockParticipants run/retry but repeatedly prevent useful progressChange coordination/backoff/admission semantics, preserving idempotency and bounded retries

In particular, suspending while holding a mutex is possible because withLock is inline; the thread can be released while the mutex remains held. It becomes a deadlock when the awaited path needs that same held resource or completes a larger wait cycle. A slow owner is not automatically deadlocked. withLock API.

Use withLock so exceptions and cooperative cancellation unwind ownership. If acquiring manually, unlock only after successful acquisition and use finally; cancellation while waiting must not unlock another caller's mutex. Cancellation/timeout can provide a defined escape for cooperative waits, but neither forces arbitrary blocking work to stop nor reverses external side effects. Wrapping the whole wait in NonCancellable, adding sleeps, indiscriminately launching new tasks, or increasing every buffer/pool can conceal the cycle and make recovery harder. Inspect both physical thread stacks and logical coroutine/resource dependencies; a thread-only deadlock detector may not see suspended task cycles.

AND-12 — Answer

Short answer: No. SharedFlow broadcasts values and can replay a configured number of past values; it is not a durable event queue. With no collector and no replay, the event is lost. Important outcomes need stored state and an explicit policy for acknowledging that the user has seen them.

Detailed explanation:

Illustrative in-memory pending notice, with acknowledgement guarded by stable ID so acknowledging an old notice cannot clear a newer one.

KOTLIN
data class PaymentNotice(val id: String, val message: String)
private val pendingNotice = MutableStateFlow<PaymentNotice?>(null)
​
fun showConfirmedPayment(operationId: String) {
    pendingNotice.value = PaymentNotice(operationId, "Payment confirmed")
}
fun acknowledgeNotice(id: String) {
    pendingNotice.update { current -> if (current?.id == id) null else current }
}

Persist important operation state separately; this single-slot example does not queue multiple notices or survive process death.

With no subscribers and replay = 0, an emitted value is lost; emit does not wait for a future screen. Extra buffer capacity does not become a durable absent-subscriber queue. replay = 1 replays the last value to each new collector, which can duplicate a snackbar/navigation effect after recreation. Neither option provides business-level exactly-once delivery. SharedFlow replay and buffering.

RequirementSuitable contractFailure to address
Current screen dataImmutable StateFlow stateEqual-value conflation; mutable nested objects
Disposable visible-screen signalShared event stream with explicit loss policyAbsent/slow collectors
Important pending resultState with stable result ID and acknowledgement; durable storage if requiredRecreation, duplicate handling, process death

🧠 A payment's canonical result comes from the backend; the UI renders pending/confirmed/failed state. An acknowledgement means the app recorded handling according to its contract, not proof a human perceived the message. A channel is also in-memory and does not solve durability or crash ambiguity. Mobile banking system design.

AND-13 — Answer

Short answer: The first collection keeps running, so execution never reaches the second one. Start each collection in a separate child coroutine inside the lifecycle-aware block. Both collections can then stop and restart with that block.

Detailed explanation:

The first collect does not normally complete, so the second is never reached. Launch child collectors:

KOTLIN
viewLifecycleOwner.lifecycleScope.launch {
    viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
        launch { viewModel.profile.collect { renderProfile(it) } }
        launch { viewModel.notifications.collect { renderNotifications(it) } }
    }
}

At stop the active block's children are cancelled; on return to STARTED a new block starts. Destroying the Fragment's view cancels its lifecycle scope. This does not necessarily stop upstream work owned by a longer-lived scope; the sharing policy matters. In a Compose Android screen, use collectAsStateWithLifecycle() for UI state and render the value. Do not launch new collectors on each recomposition. Lifecycle-aware coroutine collection.

AND-14 — Answer

Short answer: The list is an ordinary mutable collection, so Compose does not observe changes inside it. Remembering the list keeps the same object; it does not make its mutations observable. Use observable state with replacement values, or a snapshot state collection that tracks its own changes.

Detailed explanation:

🟥 An ordinary MutableList is not observable Compose state. Remembering its identity does not make in-place mutations observable.

KOTLIN
@Composable
fun TagEditor() {
    var tags by remember { mutableStateOf(listOf("Android")) }
    Column {
        Button(onClick = { tags = tags + "Kotlin" }) { Text("Add tag") }
        Text(tags.joinToString())
    }
}

A mutableStateListOf is an alternative for observed collection mutations; mutable fields inside its elements still need correct state modeling. Recomposition may be skipped or repeated; composables should be side-effect free while describing UI. Measure frame time and expensive work on representative devices instead of assuming every recomposition is a performance defect. Immutable screen state simplifies reasoning but copying and equality costs still deserve measurement. Compose state and observable collections.

AND-15 — Answer

Short answer: A screen state owner should hold the form values, apply validation, and publish the next state. Reusable controls receive values and report user actions through callbacks. This keeps business decisions out of individual widgets and makes the same form behavior easier to test.

Detailed explanation:

🟩 Give reusable controls values and callbacks; the screen state owner accepts intents, validates, and publishes the next state.

KOTLIN
@Composable
fun DisplayNameField(
    value: String,
    error: String?,
    onValueChange: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    TextField(
        value = value,
        onValueChange = onValueChange,
        modifier = modifier,
        label = { Text("Display name") },
        isError = error != null,
        supportingText = { if (error != null) Text(error) }
    )
}

A switch emits a Boolean intent; radio buttons represent one selected choice; a dropdown owns transient expansion separately from the selected domain value. The save button reflects pending/valid state, but the domain/backend still validates and deduplicates submission. Keep keyboard/focus, labels, loading, and readable errors explicit. Compose state hoisting.

Use remember for composition-lifetime UI state; rememberSaveable for small restorable UI values such as selected filters when appropriate; a ViewModel for screen business logic and data orchestration. Hoist only as far as shared ownership requires. A ViewModel's lifetime alone does not persist process death. Compose state saving.

AND-16 — Answer

Short answer: Without stable item identity, Compose can associate remembered state with a row's position as the list changes. Give each item a stable, unique key and put selection state under an owner that matches its intended lifetime. A key preserves identity across moves; it is not durable storage.

Detailed explanation:

🟥 Without explicit item identity, remembered row state can follow a position when rows reorder. Key items by a stable, unique domain identifier, never a freshly generated UUID or a mutable title.

KOTLIN
LazyColumn {
    items(tasks, key = { task -> task.id }) { task ->
        TaskRow(
            task = task,
            checked = task.id in selectedIds,
            onCheckedChange = { checked -> onSelectionChange(task.id, checked) }
        )
    }
}

This fragment hoists selection to an owner above the row. For local UI state, rememberSaveable with a suitable saver/key type may be appropriate. A key associates an item across moves; it is not durable storage and does not guarantee state retention after arbitrary removal. Persist actual task completion in the data layer, distinguish it from temporary selection, and define restoration for deleted tasks. Stable keys also help preserve item identity for effects. Compose lazy-list item keys.

AND-17 — Answer

Short answer: Restart the effect when the account it loads changes. A constant key keeps the old effect running, while a captured callback can also become outdated. Use the account as a restart key and keep the latest callback available without restarting the request just because the callback object changed.

Detailed explanation:

🟥 Unit does not change with accountId, so the running effect can load the old account and invoke an outdated callback. Restart when the account changes; capture the latest callback without restarting just because its identity changes.

KOTLIN
@Composable
fun AccountScreen(accountId: String, onLoaded: (String) -> Unit) {
    val currentOnLoaded by rememberUpdatedState(onLoaded)
    LaunchedEffect(accountId) {
        val name = accountRepository.loadName(accountId)
        ensureActive()
        currentOnLoaded(name)
    }
}

The repository is assumed stable/injected; if it changes semantically, include it in the effect's keys. Cancellation prevents publication here after a cooperative suspension/check; it does not undo a request already accepted remotely. LaunchedEffect cancels when it leaves composition. Put longer-lived screen work in a ViewModel scope; durable deferrable work needs a persisted operation and suitable scheduler. Use DisposableEffect for paired registration/cleanup. Avoid doing IO directly in the composable body. Compose effect keys and rememberUpdatedState.

AND-18 — Answer

Short answer: A ViewModel can keep screen data across configuration changes, but process death removes it. Save small reconstruction values, such as a query or selected ID, with saved-state APIs; keep important records in durable storage. Rebuild large fetched data after restoration and keep credentials out of saved UI state.

Detailed explanation:

Illustrative ViewModel: store a reconstruction value in SavedStateHandle, not the fetched catalog or credentials.

KOTLIN
class CatalogViewModel(private val savedState: SavedStateHandle) : ViewModel() {
    val query: StateFlow<String> = savedState.getStateFlow("query", "")
    fun updateQuery(value: String) {
        savedState["query"] = value.take(200)
    }
    fun selectItem(id: String) {
        savedState["selectedItemId"] = id
    }
}

The input bound is an example product policy; reconstruct catalog data through the repository after restoration.

ValueOwner/restorationReason
Query or selected IDUI state owner; small saveable value or SavedStateHandleReconstruct a user's screen context
CatalogRepository/local database; reconstruct presentationLarge fetched data does not belong in saved-state bundles
Pending order intentDurable operation/outbox with stable IDMust survive process termination and reconcile with server
Authentication secretDedicated security/storage boundaryKeep out of UI saved state, route arguments, and logs

A ViewModel commonly survives configuration recreation but not process death. Saved-state restoration depends on the Android saved-state/task lifecycle and supported value formats; it is not a general guarantee after force-stop, task dismissal, or a fresh launch. Persist business-critical data independently. Save minimal reconstruction keys rather than large graphs; verify restoration with real recreation/process scenarios as well as focused tests. Android UI-state saving and ViewModel restoration.

AND-19 — Answer

Short answer: Pass the stable order ID and only the small parameters needed to locate the screen. The destination should load current data for the authenticated user and handle missing or unavailable orders. A valid route identifies a requested destination; it does not grant permission to view or change the order.

Detailed explanation:

Illustrative route-input boundary; this example deliberately accepts a bounded ASCII order-ID format, which must match the real API contract.

KOTLIN
data class OrderRoute(val orderId: String)
​
fun parseOrderRoute(rawId: String): OrderRoute? =
    rawId.takeIf { it.matches(Regex("[A-Za-z0-9_-]{1,64}")) }
        ?.let(::OrderRoute)
​
suspend fun loadOrder(route: OrderRoute, repository: OrderRepository): Order =
    repository.authorizedOrder(route.orderId)

authorizedOrder is an application dependency that uses the current authenticated session and server authorization; syntax validation alone grants no access.

Pass a stable order ID and necessary small route parameters, then load authorized data through the destination's state/repository boundary. Keep navigation orchestration at the app/feature host; reusable content receives navigation callbacks. Define Back versus Up behavior and restore the intended stack. Pin the Navigation implementation/version before choosing exact route APIs. Android navigation.

🟨 Treat an external ID as untrusted input. Validate its form, recheck the session, and let the server authorize access; handle missing/forbidden orders without displaying stale data from a previous account. A confirmation screen should render the server's result for a stable operation ID. Local button disabling reduces accidental taps but cannot stop retries, another device, or a manipulated client. Route typing only checks representation, not permission. Mobile architecture boundaries, distributed-systems fundamentals.

AND-20 — Answer

Short answer: The action needs a meaningful accessible name, the right interaction semantics, and a usable target. A decorative icon may omit its description when its parent supplies the name, but an unlabeled icon cannot be the only description of an action. Verify the whole interaction with assistive technology.

Detailed explanation:

🟩 Prefer a semantic action component and a localized meaningful name:

KOTLIN
IconButton(onClick = onDeleteDraft) {
    Icon(
        imageVector = Icons.Default.Delete,
        contentDescription = stringResource(R.string.delete_draft)
    )
}

Here onDeleteDraft and the string resource are app-provided. contentDescription = null is appropriate for a decorative icon whose surrounding component already supplies its name; the original icon is the only action label. Ensure a usable touch target and avoid duplicate announcements. A chart needs a useful summary and access to important values/trends, with semantic state/actions when interactive. Compose semantics.

Test TalkBack reading order, keyboard/switch access, focus after deletion/dialog dismissal, large text, contrast, and touch targets on devices. Do not use color alone for errors or selection. Semantics tests verify selected contracts but cannot prove the spoken journey is understandable.

AND-21 — Answer

Short answer: Save the edit and a record of the pending server operation in the same local database transaction. The UI reads that local state while a separate synchronization process sends the pending work. A stable operation ID and conflict policy let the app recover after retries or restarts without pretending the device and server share one transaction.

Detailed explanation:

Illustrative DAO transaction for a Room 2.x-style API; entity/DAO definitions are application-specific. Both writes use one database, and there is no network request in this transaction.

KOTLIN
@Dao
abstract class EditDao {
    @Update abstract suspend fun updateNote(note: NoteEntity)
    @Insert abstract suspend fun insertPending(operation: PendingEditEntity)
​
    @Transaction
    open suspend fun saveEdit(note: NoteEntity, pending: PendingEditEntity) {
        require(note.id == pending.noteId)
        updateNote(note)
        insertPending(pending)
    }
}

Create the pending operation ID before this call and preserve it for retries; adapt annotations/imports to the pinned Room major version.

🧠 The UI observes local database state through the repository. A refresh updates that store; user edits atomically save the local mutation and its outbox record, including a stable operation ID and base version. A sync worker submits pending operations, reconciles server versions, and transactionally records acknowledgements/local canonical changes. Use suspend for one-shot DAO operations and observable queries for the read path, using the pinned Room version's APIs. Android offline-first data layer, Room asynchronous queries.

🟨 The transaction protects local consistency, not a device/server distributed commit. Keep HTTP outside the local transaction, make server processing idempotent, and recover from either side completing first. Resolve conflicts using domain policy: version rejection and user resolution, a safe merge, or explicitly accepted last-write-wins. Do not silently overwrite meaningful concurrent edits. Preserve pending operations through migrations; test edits during refresh, duplicate delivery, and account switching. Room transactions, shared offline-first design.

AND-22 — Answer

Short answer: Not by itself. WorkManager can schedule persistent background work, but a worker may restart after the server already accepted its request. Reuse a stored operation ID and make the server recognize repeated delivery of that same operation. Unique work reduces duplicate local scheduling, not duplicate business effects.

Detailed explanation:

Illustrative enqueue step after durably saving the operation; the worker reloads that same operation and reuses its server idempotency key.

KOTLIN
val request = OneTimeWorkRequestBuilder<UploadEditWorker>()
    .setInputData(workDataOf("operationId" to operation.id))
    .setConstraints(
        Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
    )
    .build()
workManager.enqueueUniqueWork(
    "upload-edit:${operation.id}", ExistingWorkPolicy.KEEP, request
)

UploadEditWorker, operation, and workManager are app dependencies. A reconciliation path must cover a crash between persistence and enqueue.

WorkManager is for persistent scheduled work subject to constraints and platform scheduling; it is not an exact clock or an uninterrupted execution guarantee. Unique work and an explicit existing-work policy reduce duplicate local scheduling. They do not prove that an HTTP mutation has never previously succeeded. WorkManager scheduling, unique-work policies.

🟩 Persist the operation before scheduling, reuse its idempotency key on retry, and have the backend durably bind that key to the authenticated operation/payload and result. On restart, retrieve/retry the same operation and record its acknowledgement locally. A timeout is an unknown outcome, not proof of failure. Retry bounded transient transport/server failures with backoff; treat permanent validation failures as terminal and credential failures through a defined refresh/re-auth path. Network constraints are scheduling hints, not proof a request will succeed. Address quota, cancellation, account ownership, and a reconciliation trigger if scheduling is interrupted.

AND-23 — Answer

Short answer: No. Keystore can help protect cryptographic keys, but it cannot make everything running on the device trustworthy. The server must authorize the user and enforce payment rules; shared service secrets must not be embedded in the app. Biometric success and hidden UI controls do not replace those server checks.

Detailed explanation:

Illustrative telemetry boundary: allow only operation metadata, not a request body, token, or account identifier.

KOTLIN
data class PaymentOutcomeMetric(val outcome: String, val retryCount: Int)
​
fun recordPaymentOutcome(metric: PaymentOutcomeMetric) {
    require(metric.outcome in setOf("confirmed", "declined", "unknown"))
    require(metric.retryCount >= 0)
    analytics.record("payment_outcome", mapOf(
        "outcome" to metric.outcome,
        "retry_count" to metric.retryCount.toString()
    ))
}

analytics is an approved app dependency; operational policy must still govern retention, access, consent, and aggregation.

🟥 An APK cannot keep an embedded service secret confidential from its user. Remove shared backend credentials from the client, use narrowly scoped user credentials, enforce authorization and payment rules on the server, and redact tokens/personal data from telemetry. Biometric confirmation can gate a local action/key use; it does not grant arbitrary backend permission.

Android Keystore protects cryptographic key material and can restrict key use. Hardware backing depends on device capabilities and key configuration; verify the actual security properties required. It is not a generic database for arbitrary secrets, does not sanitize logs, and cannot make a compromised app's requests inherently trustworthy. Android Keystore protections and limits.

Use platform TLS validation, least-privilege storage/access, account-scoped caches and clearing/revalidation on sign-out. Choose pinning only with a rotation/recovery plan. Define threat-model-driven tests for exported components, deep links, session changes, replay/duplicate submissions, and sensitive screenshots/notifications. Networking and security, banking architecture.

AND-24 — Answer

Short answer: Control request completion in a fake repository and deliberately finish the older request last. The test should prove that only the current result becomes visible, including after cancellation or an account change. Then verify the affected user journey on devices and monitor the staged release instead of relying on a passing test alone.

Detailed explanation:

Illustrative coroutine regression-test body: a controllable fake exposes request completions and the ViewModel is constructed with the test scope/dispatcher. runCurrent starts scheduled work without wall-clock sleeps.

KOTLIN
@Test fun newestSearchRemainsVisible() = runTest {
    val repository = ControlledSearchRepository()
    val model = makeSearchModel(repository, backgroundScope)
    model.search("ca")
    runCurrent()
    model.search("cat")
    runCurrent()
    repository.complete("cat", listOf("cat"))
    runCurrent()
    repository.complete("ca", listOf("car"))
    runCurrent()
    assertEquals(listOf("cat"), model.results.value)
}

The fake deliberately permits obsolete completion; its API and construction helper are test-fixture contracts, not library APIs.

🟩 Use a fake repository with explicitly controlled completions, injected dispatchers, and runTest. Complete requests in reverse order and assert state never regresses; cancel a request and assert no later success/error publication. Share one test scheduler across test dispatchers. Virtual time controls coroutine scheduling; it does not exercise true multithreaded contention or prove an atomic implementation safe. Add targeted real-dispatcher stress/invariant tests where that risk exists, without relying on sleeps to force ordering. Android coroutine testing.

Test UI input/loading/error/submit interactions, row identity after reorder, and restoration of the selected ID/query. Exercise lifecycle stop/start and process recreation separately. Integration tests should kill/restart processing between remote success and local acknowledgement and verify the server returns the same operation result.

The lead owns the cross-platform contract: latest user intent wins, operation identity is stable, and canonical payment state comes from the backend. Android owns lifecycle/coroutine integration; iOS owns actor/task integration; backend owns authorization/idempotency. Agree observable outcomes and staged rollout thresholds, monitor stale-result/duplicate-operation signals without sensitive payloads, and retain a mitigation path. Do not require Kotlin and Swift to mirror each other's mechanisms. Architecture decisions and incident handling.

AND-25 — Answer

Short answer: Register the listener when collection starts and remove it when that collection ends or is cancelled. CallbackFlow and awaitClose provide a coroutine-friendly place to pair those steps. Choose buffering deliberately so a slow screen does not create an unbounded backlog or silently lose values the product needs.

Detailed explanation:

Use callbackFlow for a multi-shot callback API, keep it alive with awaitClose, and release the subscription there. Choose an explicit loss policy: a live battery indicator can keep only the latest value. Each collector registers its own listener unless the owner deliberately shares the flow. A callback racing with cancellation must tolerate a failed send.

Scenario and complete adapter

A device-details screen shows the newest battery percentage. Intermediate percentages are disposable; payment confirmations would need a different delivery contract. This standalone adapter uses kotlinx-coroutines-core. The SDK contract below requires thread-safe registration/cleanup, allows callbacks from any thread, and makes cancel() nonthrowing and idempotent. An SDK that requires main-thread registration needs that additional boundary.

KOTLIN
import java.io.IOException
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.buffer
import kotlinx.coroutines.flow.callbackFlow
​
fun interface BatterySubscription {
    fun cancel()
}
​
interface BatteryListener {
    fun onPercentage(value: Int)
    fun onFailure(error: IOException)
}
​
interface BatterySdk {
    fun subscribe(deviceId: String, listener: BatteryListener): BatterySubscription
}
​
class BatteryRepository(private val sdk: BatterySdk) {
    fun percentages(deviceId: String): Flow<Int> = callbackFlow {
        require(deviceId.isNotBlank())
        val listener = object : BatteryListener {
            override fun onPercentage(value: Int) {
                if (value in 0..100) {
                    trySend(value)
                }
            }
​
            override fun onFailure(error: IOException) {
                close(error)
            }
        }
        val subscription = sdk.subscribe(deviceId, listener)
        awaitClose { subscription.cancel() }
    }.buffer(Channel.CONFLATED)
}

trySend does not block the SDK thread. Its failure after close/cancellation is intentionally ignored because this stream permits losing a value when no consumer remains. Conflation avoids an unbounded backlog while a slow screen renders. An error closes collection exceptionally; retry/reconnection belongs to a separately chosen policy. The registration contract must not leave an active subscription behind if subscribe throws before returning its handle.

Verify and discuss the tradeoff

Use a fake SDK to count subscriptions and cancellations. Start collection, emit several percentages, cancel the collector, and assert cleanup happens once. Then invoke the retained old callback and assert no screen update. Collect twice and expect two registrations. If both consumers should share one hardware subscription, apply an explicitly owned shareIn/stateIn policy and test its stop timeout; do not hide a process-long scope in the adapter. See callbackFlow ownership and cleanup and conflation.

AND-26 — Answer

Short answer: Use one atomic decision to accept a result, failure, or cancellation, and connect cancellation to the request handle. Checking whether a continuation is active before resuming it is insufficient because two callbacks can both pass that check. The adapter must also tolerate a callback arriving during registration.

Detailed explanation:

Use suspendCancellableCoroutine for one result, arbitrate terminal callbacks atomically, and pair cancellation with the SDK request handle. A separate check of isActive does not reserve completion: two callbacks can both see true. Cancellation may win after a successful callback but before resumed code runs, so at-most-one accepted callback is not a guarantee that the caller receives a value.

Scenario and full bridge

A profile screen loads a membership card through a legacy SDK. The returned card is ordinary immutable data, not a resource that needs closing. The example requires kotlinx-coroutines-core. fetch must return promptly, and its handle's cancellation must be thread-safe, nonthrowing, and idempotent. A registration failure throws IOException without leaving an unreturned live request. Those are SDK assumptions to verify, not guarantees supplied by coroutines.

KOTLIN
import java.io.IOException
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlinx.coroutines.suspendCancellableCoroutine
​
data class MembershipCard(val memberId: String, val tier: String)
​
fun interface CardRequest {
    fun cancel()
}
​
interface CardCallback {
    fun onSuccess(card: MembershipCard)
    fun onFailure(error: IOException)
}
​
interface CardSdk {
    fun fetch(memberId: String, callback: CardCallback): CardRequest
}
​
suspend fun CardSdk.awaitCard(memberId: String): MembershipCard {
    require(memberId.isNotBlank())
    return suspendCancellableCoroutine { continuation ->
        val terminal = AtomicBoolean(false)
        val handle = AtomicReference<CardRequest?>(null)
​
        continuation.invokeOnCancellation {
            terminal.set(true)
            handle.getAndSet(null)?.cancel()
        }
​
        val callback = object : CardCallback {
            override fun onSuccess(card: MembershipCard) {
                if (terminal.compareAndSet(false, true)) {
                    continuation.resume(card)
                }
            }
​
            override fun onFailure(error: IOException) {
                if (terminal.compareAndSet(false, true)) {
                    continuation.resumeWithException(error)
                }
            }
        }
​
        val request = try {
            fetch(memberId, callback)
        } catch (failure: IOException) {
            if (terminal.compareAndSet(false, true)) {
                continuation.resumeWithException(failure)
            }
            return@suspendCancellableCoroutine
        }
​
        handle.set(request)
        if (continuation.isCancelled) {
            handle.getAndSet(null)?.cancel()
        }
    }
}

The final cancellation check closes the registration race: cancellation can run while fetch is still obtaining the handle. Either the handler removes the published handle, or the post-registration check does. A synchronous callback can finish before the handle is returned, and competing success/failure callbacks still accept only one terminal signal. A callback accepted just before cancellation does not defeat the continuation's prompt-cancellation behavior.

Verify and discuss the tradeoff

Test synchronous success, ordinary failure, duplicate success, simultaneous success/failure, cancellation during registration, and a callback after cancellation. Assert the caller sees one terminal outcome and the cancellation handle is invoked according to its contract. A local atomic guard cannot stop the remote request's business effect. If a callback returns a socket/file/image resource, also provide the continuation's resource-on-cancellation cleanup for a value lost during dispatch; this data-only example does not cover resource transfer. See suspendCancellableCoroutine and prompt cancellation.

AND-27 — Answer

Short answer: StateFlow does not emit a replacement that compares equal to its current value. If both values share a list that was already mutated, the old snapshot has changed too, so there is no reliable before-and-after comparison. Publish replacement state whose nested data is not shared mutable state.

Detailed explanation:

StateFlow suppresses equal values. Mutating a list already held by the current state also mutates the alleged old snapshot; copying the outer object with that same list does not create a meaningful before/after value. Publish a new list of immutable elements through one owner. StateFlow represents the latest state and may skip intermediate updates for slow collectors.

Scenario and complete state owner

A cart badge and checkout screen observe the same cart. The owner changes quantities by replacing value objects; UI code receives a read-only StateFlow. This example uses kotlinx-coroutines-core. Product IDs and quantities are illustrative local rules; inventory and payment validation still belong at their authoritative boundaries.

KOTLIN
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
​
data class CartLine(val productId: String, val quantity: Int)
data class CartSnapshot(val lines: List<CartLine> = emptyList())
​
class CartStore {
    private val mutableState = MutableStateFlow(CartSnapshot())
    val state: StateFlow<CartSnapshot> = mutableState.asStateFlow()
​
    fun setQuantity(productId: String, quantity: Int) {
        require(productId.isNotBlank())
        require(quantity in 0..99)
        mutableState.update { old ->
            val withoutProduct = old.lines.filterNot { it.productId == productId }
            val nextLines = if (quantity == 0) {
                withoutProduct
            } else {
                withoutProduct + CartLine(productId, quantity)
            }
            CartSnapshot(nextLines.sortedBy { it.productId })
        }
    }
}

Every element contains only immutable values, and this owner neither retains a caller-supplied mutable list nor mutates a previously published one. Kotlin's read-only List interface alone is not a deeply immutable collection guarantee; callers must respect that contract. Use a persistent immutable collection library when enforcing that stronger boundary is a requirement. The update lambda is pure because contention can evaluate it again.

Verify and discuss the tradeoff

Save val previous = store.state.value, change a quantity, and assert previous.lines is unchanged. A collector should see a new unequal state; setting the same quantities should not force a redundant emission. Reorder inputs and verify sorting produces the intended value equality. Do not force updates with random IDs to conceal mutable aliases. Audit/history events need a separately designed durable log rather than relying on observing every StateFlow assignment. See StateFlow equality conflation and Kotlin read-only versus mutable collection interfaces.

AND-28 — Answer

Short answer: Use bounded buffering with suspension when the producer can be slowed and every value must be processed. Use conflation when only the newest waiting value matters, and latest-processing cancellation when newer work should replace ongoing work. Cancellation remains cooperative and cannot undo an external action that already happened.

Detailed explanation:

Use a bounded buffer with suspending overflow when every in-session value matters, conflate when only the newest pending value matters, and collectLatest when a new value makes the running collector obsolete. Cancellation remains cooperative: CPU work needs checks and an appropriate dispatcher. None of these operators makes events durable or reverses a request already accepted elsewhere.

Scenario and three concrete policies

A dashboard processes each local audit record, paints the newest progress, and builds only the newest expensive preview. The following full declarations use kotlinx-coroutines-core; production injects a CPU dispatcher such as Dispatchers.Default. These functions are suspend functions owned by the caller's lifecycle/scope. The audit sink is assumed nonblocking/main-safe or responsible for dispatching its actual blocking IO.

KOTLIN
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.buffer
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.conflate
import kotlinx.coroutines.withContext
​
data class AuditRecord(val operationId: String, val outcome: String)
data class PreviewInput(val samples: List<Int>)
data class Preview(val normalized: List<Double>)
​
interface AuditSink {
    suspend fun persist(record: AuditRecord)
}
​
suspend fun persistAudit(records: Flow<AuditRecord>, sink: AuditSink) {
    records.buffer(capacity = 16).collect { sink.persist(it) }
}
​
suspend fun renderProgress(values: Flow<Int>, render: suspend (Int) -> Unit) {
    values.conflate().collect { render(it) }
}
​
suspend fun renderPreviews(
    inputs: Flow<PreviewInput>,
    cpuDispatcher: CoroutineDispatcher,
    render: (Preview) -> Unit
) {
    inputs.collectLatest { input ->
        val preview = withContext(cpuDispatcher) {
            val output = ArrayList<Double>(input.samples.size)
            input.samples.forEachIndexed { index, sample ->
                if (index % 256 == 0) currentCoroutineContext().ensureActive()
                output.add(sample.coerceIn(0, 1000) / 1000.0)
            }
            Preview(output)
        }
        currentCoroutineContext().ensureActive()
        render(preview)
    }
}

The bounded audit buffer overlaps production and collection, then suspends upstream when full. It preserves values only within a successful collection run; durable records require persistence before acknowledging their source. Conflation drops superseded pending progress values but finishes the current render. Latest collection instead cancels the previous preview action. A CPU loop that never suspends or checks cancellation can delay the next preview despite that policy.

PolicySlow consumer behaviorSuitable example
buffer(16) with default suspend overflowQueue up to capacity, then suspend upstreamOrdered in-session processing with bounded backlog
conflate()Replace pending intermediate values with the newestCurrent progress percentage
collectLatestCancel the previous action before processing the latestDisposable preview computation

Verify and discuss the tradeoff

Gate the sink/renderer with a fake completion, emit a known sequence, and inspect which values begin and finish. Cancel during preview computation and assert no obsolete preview is rendered. Measure CPU/frame time on representative devices; a small cancellation-check interval trades check overhead for responsiveness. Do not apply latest-only cancellation to a payment submission as a deduplication strategy. See buffering, conflation, latest collection, and cooperative CPU cancellation.

AND-29 — Answer

Short answer: Use a shared concurrency limit around the active request, and associate each result with its original input position. Structured child work keeps cancellation under the caller. Limiting active requests does not automatically limit how many waiting tasks are created, so the queue also needs a bound for very large inputs.

Detailed explanation:

Keep a shared Semaphore at the request owner, acquire a permit around each active request, and await structured children in the input order. Give each request a timeout and choose whether one failure aborts the batch. A semaphore bounds work inside its protected region; it does not stop creating an arbitrarily large list of waiting coroutines.

Scenario and complete bounded batch

A comparison sheet accepts at most 100 product IDs. This all-or-nothing example uses kotlinx-coroutines-core. The main-safe ProductApi must suspend cooperatively, honor cancellation, and return detached immutable data. The loader instance is shared by the screen's request owner so overlapping calls share the same four active-request permits.

KOTLIN
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import kotlinx.coroutines.withTimeout
​
data class ProductDetails(val id: String, val name: String, val priceCents: Long)
​
interface ProductApi {
    suspend fun details(productId: String): ProductDetails
}
​
class ProductBatchLoader(
    private val api: ProductApi,
    maxConcurrent: Int = 4,
    private val requestTimeoutMillis: Long = 5_000
) {
    init {
        require(maxConcurrent > 0)
        require(requestTimeoutMillis > 0)
    }
​
    private val requests = Semaphore(maxConcurrent)
​
    suspend fun load(productIds: List<String>): List<ProductDetails> {
        require(productIds.size <= 100)
        require(productIds.all { it.isNotBlank() })
        return coroutineScope {
            productIds.map { id ->
                async {
                    requests.withPermit {
                        withTimeout(requestTimeoutMillis) { api.details(id) }
                    }
                }
            }.awaitAll()
        }
    }
}

The timeout starts after obtaining a permit, so it bounds the active call rather than time spent waiting in the local queue. Add a separate operation deadline if the whole comparison must finish within a bound. Results follow productIds, not network completion order. A child failure or timeout fails this normal structured scope and cancels siblings; withPermit releases acquired permits on exit. Cancellation cannot force a badly behaved blocking SDK to stop.

Verify and discuss the tradeoff

Use a fake API that records current and maximum active calls and exposes one completion per request. Assert the peak stays at four, complete IDs out of order, and assert the returned order matches the input. Cancel while some children are waiting and prove a later batch can still obtain every permit. For unbounded streams or huge lists, use a bounded producer/worker pipeline rather than creating one child per input. If partial results are required, model success/failure per item and handle expected errors without swallowing cancellation. See Semaphore permits and awaitAll failure/cancellation.

AND-30 — Answer

Short answer: Read the old value and calculate its replacement inside the same DataStore edit transaction. A read performed beforehand can become stale before the write, causing concurrent increments to overwrite one another. Share the correctly scoped DataStore instance rather than creating one for every screen.

Detailed explanation:

Read and modify the counter inside the same DataStore edit transform. Reading beforehand creates a stale snapshot that two callers can both increment into the same value. Define one DataStore instance per file in a process, expose its Flow for observation, and keep writes suspending. Blocking main or creating multiple instances does not repair the transaction boundary.

Scenario and complete Preferences DataStore owner

A reader app counts successfully opened lessons. This Android example needs androidx.datastore:datastore-preferences and kotlinx-coroutines-core, with compatible pinned versions. Declare the extension once at file level and obtain it through the application context; do not declare another delegate for the same file in each screen.

KOTLIN
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
​
val Context.lessonUsageStore: DataStore<Preferences> by preferencesDataStore(
    name = "lesson_usage"
)
​
class LessonUsageRepository(private val store: DataStore<Preferences>) {
    private val readCountKey = longPreferencesKey("read_count")
​
    val readCount: Flow<Long> = store.data.map { preferences ->
        preferences[readCountKey] ?: 0L
    }
​
    suspend fun recordRead(): Long {
        val updated = store.edit { preferences ->
            val previous = preferences[readCountKey] ?: 0L
            check(previous < Long.MAX_VALUE) { "Read counter exhausted" }
            preferences[readCountKey] = previous + 1L
        }
        return updated[readCountKey] ?: 0L
    }
}
​
fun lessonUsageRepository(context: Context): LessonUsageRepository =
    LessonUsageRepository(context.applicationContext.lessonUsageStore)

Serialized transforms read the then-current value and atomically persist the replacement. A failed write propagates instead of pretending success. Present IO failure through the UI's error contract; do not silently convert a failed increment into an acknowledged read. Keep transforms short and local: network side effects inside a storage transform create unwanted coupling and do not form a distributed transaction.

Verify and discuss the tradeoff

With a test-owned store and temporary file, launch many increments, await all of them, and verify the persisted total equals the number of successful writes. Close the test store's scope before recreating another instance for that file, then verify the value survives reopening. This local counter counts calls, not globally unique human reads; deduplication or cross-device reporting needs stable identity and a separate contract. For related rows, large data, or referential integrity use Room. See DataStore consistency, instance rules, and intended scope.

AND-31 — Answer

Short answer: Read the related rows in one transaction so they describe the same database snapshot. Replace related rows in a single write transaction as well, so readers cannot observe a half-finished update. Separate flows or individually atomic writes do not automatically provide that combined view.

Detailed explanation:

An @Relation aggregate may require several database queries. Put that read in @Transaction so parent and child rows form one coherent snapshot, and replace all related rows in one write transaction. Atomic individual statements alone still permit an interleaving between statements. Combining independently observed flows may pair values from different emissions.

Scenario and complete Room declarations

A delivery screen displays an order total and its lines. This example targets the Room 2.x annotation APIs and needs pinned androidx.room:room-runtime, room-ktx where required by that version, and the matching room-compiler processor through KSP. It is a local cache replacement, not a remote payment transaction. The app opens this database once through its application dependency container and supplies reviewed migrations when the schema changes.

KOTLIN
import androidx.room.Dao
import androidx.room.Database
import androidx.room.Embedded
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.Insert
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.Relation
import androidx.room.RoomDatabase
import androidx.room.Transaction
import androidx.room.Update
​
@Entity(tableName = "orders")
data class OrderEntity(
    @PrimaryKey val id: String,
    val revision: Long,
    val totalCents: Long
)
​
@Entity(
    tableName = "order_lines",
    primaryKeys = ["orderId", "lineNumber"],
    foreignKeys = [ForeignKey(
        entity = OrderEntity::class,
        parentColumns = ["id"],
        childColumns = ["orderId"],
        onDelete = ForeignKey.CASCADE
    )],
    indices = [Index(value = ["orderId"])]
)
data class OrderLineEntity(
    val orderId: String,
    val lineNumber: Int,
    val title: String,
    val quantity: Int,
    val unitPriceCents: Long
)
​
data class OrderWithLines(
    @Embedded val order: OrderEntity,
    @Relation(parentColumn = "id", entityColumn = "orderId")
    val lines: List<OrderLineEntity>
)
​
@Dao
abstract class OrderDao {
    @Transaction
    @Query("SELECT * FROM orders WHERE id = :orderId")
    abstract suspend fun load(orderId: String): OrderWithLines?
​
    @Insert
    protected abstract suspend fun insertOrder(order: OrderEntity)
​
    @Update
    protected abstract suspend fun updateOrder(order: OrderEntity): Int
​
    @Query("DELETE FROM order_lines WHERE orderId = :orderId")
    protected abstract suspend fun deleteLines(orderId: String)
​
    @Insert
    protected abstract suspend fun insertLines(lines: List<OrderLineEntity>)
​
    @Transaction
    open suspend fun replaceSnapshot(
        order: OrderEntity,
        lines: List<OrderLineEntity>
    ) {
        require(order.id.isNotBlank() && order.totalCents >= 0)
        require(lines.all { it.orderId == order.id && it.quantity > 0 })
        require(lines.map { it.lineNumber }.distinct().size == lines.size)
        if (updateOrder(order) == 0) insertOrder(order)
        deleteLines(order.id)
        insertLines(lines)
    }
}
​
@Database(
    entities = [OrderEntity::class, OrderLineEntity::class],
    version = 1,
    exportSchema = true
)
abstract class OrdersDatabase : RoomDatabase() {
    abstract fun orders(): OrderDao
}

A failed insertion rolls back the replacement rather than exposing an order with partially replaced lines. The returned relation does not promise line ordering; sort by lineNumber for display or use an explicitly ordered query when order is part of the read contract. This example deliberately does not reject older server revisions; the repository must define freshness/conflict policy before choosing which snapshot to submit.

Verify and discuss the tradeoff

Use a real test database, replace one snapshot with another, and assert a reader sees a coherent old or new aggregate. Use a test-only SQLite insert trigger that aborts insertion of a chosen line, then assert the old rows survive rollback after replacement throws. Verify migrations, foreign-key enforcement, and query ordering separately. Keep HTTP outside this transaction; a local read/write boundary cannot coordinate a server commit. See Room one-to-many relations and @Transaction read/write behavior.

AND-32 — Answer

Short answer: Use one controllable test scheduler to move virtual time to the debounce boundary, and a fake repository to control request completion. Assert when requests start and which request is cancelled. Then finish an obsolete request deliberately and verify that it cannot replace the latest visible result.

Detailed explanation:

Inject the query stream and repository, use one test scheduler, advance virtual time to the debounce boundary, then run work scheduled exactly at that instant. A controlled fake makes request completion and cancellation observable. Here the old request is cancelled when the next debounced query reaches flatMapLatest, not immediately when the user types another character.

Scenario, full pipeline, and complete unit test

A catalog search waits 300 ms after typing settles. This standalone JVM test needs compatible pinned kotlinx-coroutines-core, kotlinx-coroutines-test, and JUnit 4 dependencies. Preview/experimental APIs are explicitly opted in; confirm those annotations against the pinned library. The fake's mutable bookkeeping is confined to the single test scheduler.

KOTLIN
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
​
interface TypeaheadRepository {
    suspend fun search(query: String): List<String>
}
​
@OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class)
fun typeaheadResults(
    queries: Flow<String>,
    repository: TypeaheadRepository
): Flow<List<String>> = queries
    .debounce(300)
    .distinctUntilChanged()
    .flatMapLatest { query ->
        flow { emit(repository.search(query)) }
    }
​
class ControlledTypeaheadRepository : TypeaheadRepository {
    val started = mutableListOf<String>()
    val cancelled = mutableSetOf<String>()
    private val responses = mutableMapOf<String, CompletableDeferred<List<String>>>()
​
    override suspend fun search(query: String): List<String> {
        val response = CompletableDeferred<List<String>>()
        check(responses.put(query, response) == null)
        started.add(query)
        return try {
            response.await()
        } catch (cancellation: CancellationException) {
            cancelled.add(query)
            throw cancellation
        }
    }
​
    fun complete(query: String, rows: List<String>) {
        checkNotNull(responses[query]).complete(rows)
    }
}
​
@OptIn(ExperimentalCoroutinesApi::class)
class TypeaheadTest {
    @Test
    fun debouncesAndDiscardsCancelledRequest() = runTest {
        val queries = MutableSharedFlow<String>()
        val repository = ControlledTypeaheadRepository()
        val rendered = mutableListOf<List<String>>()
        val collector = backgroundScope.launch {
            typeaheadResults(queries, repository).collect { rendered.add(it) }
        }
        runCurrent()
​
        queries.emit("ca")
        runCurrent()
        advanceTimeBy(299)
        assertTrue(repository.started.isEmpty())
​
        queries.emit("cat")
        runCurrent()
        advanceTimeBy(299)
        assertTrue(repository.started.isEmpty())
        advanceTimeBy(1)
        runCurrent()
        assertEquals(listOf("cat"), repository.started)
​
        queries.emit("cats")
        runCurrent()
        assertTrue(repository.cancelled.isEmpty())
        advanceTimeBy(300)
        runCurrent()
        assertEquals(listOf("cat", "cats"), repository.started)
        assertTrue("cat" in repository.cancelled)
​
        repository.complete("cats", listOf("cats"))
        runCurrent()
        repository.complete("cat", listOf("obsolete cat"))
        runCurrent()
        assertEquals(listOf(listOf("cats")), rendered)
        collector.cancel()
        runCurrent()
    }
}

advanceTimeBy deliberately does not execute work scheduled exactly at the new boundary; runCurrent does. backgroundScope owns the non-completing collector so it cannot keep the test alive indefinitely. The obsolete CompletableDeferred can still complete, but its cancelled waiter no longer publishes that result. This fake models a cancellable suspending repository; a broken callback bridge that ignores cancellation needs a separate adapter test such as AND-26.

Verify and discuss the tradeoff

If typing must invalidate the current result immediately, move the cancellation boundary to the raw query stream and put the debounce delay inside that latest-only operation, then write the corresponding timing test. Also specify blank-query behavior, error UI, and repeat-query policy; this focused pipeline propagates failures and does not retry. Virtual scheduling proves the chosen order and time contract; use separate real-dispatcher tests for true shared-memory races. See Android coroutine testing and scheduler ownership, debounce, and advanceTimeBy boundary semantics.

AND-33 — Answer

Short answer: Store the document ID with the small saved draft and reject restored data for a different document. Saveable inputs can reset remembered state during composition, but they do not by themselves validate ownership of restored data. Important edits still need durable storage beyond UI reconstruction.

Detailed explanation:

Save only the small draft, include its document ID in the saved representation, and reject a restored ID that differs from the current document. rememberSaveable inputs reset state when they change during composition; restoration does not validate the previously saved inputs. A draft saver supports UI reconstruction, while important edits need independent durable storage.

Scenario and implementation

A support agent switches between two ticket notes. Restoring ticket B must never display ticket A's unfinished text. This illustrative Compose/Material 3 component assumes documentId is a stable authorized route identifier and the caller supplies the initial text. It uses a 500-character product limit to keep this example small; it is not a platform bundle limit.

KOTLIN
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
​
data class NoteDraft(val documentId: String, val text: String)
​
@Composable
fun NoteDraftEditor(
    documentId: String,
    initialText: String,
    modifier: Modifier = Modifier
) {
    require(documentId.isNotBlank() && documentId.length <= 128)
    val draftSaver = remember(documentId) {
        listSaver<NoteDraft, String>(
            save = { listOf(it.documentId, it.text) },
            restore = { values ->
                val owner = values.getOrNull(0)
                val text = values.getOrNull(1)
                if (values.size == 2 && owner == documentId &&
                    text != null && text.length <= 500
                ) {
                    NoteDraft(documentId, text)
                } else {
                    null
                }
            }
        )
    }
    var draft by rememberSaveable(documentId, stateSaver = draftSaver) {
        mutableStateOf(NoteDraft(documentId, initialText.take(500)))
    }
    OutlinedTextField(
        value = draft.text,
        onValueChange = { text -> draft = draft.copy(text = text.take(500)) },
        label = { Text("Draft note") },
        modifier = modifier
    )
}

The saver closes over the current document identity and validates the restored shape. Changing the document resets the draft; changing initialText alone does not overwrite an in-progress edit. Resolve remote changes and unsaved edits through an explicit product policy. Keep credentials, attachments, and full fetched documents out of this saved state. Saveable inputs and restoration, small UI-state saving.

Check and tradeoff

Use StateRestorationTester to restore the same document and confirm the draft returns, then restore with a different ID and confirm initialization uses that document's text. Also exercise actual activity recreation. Saved-state restoration is not a substitute for autosaving important work to a database and does not promise recovery after every task dismissal or fresh launch. A custom saver adds validation/schema maintenance; a primitive value is simpler when ownership and representation already fit.

AND-34 — Answer

Short answer: The same effect that registers the listener should remove it when its owner changes or the effect leaves composition. DisposableEffect pairs those actions, while rememberUpdatedState lets the listener call the latest callback. Registering directly while drawing the composable can add listeners repeatedly without reliable cleanup.

Detailed explanation:

Use DisposableEffect(lifecycleOwner) to pair observer registration with removal, and use rememberUpdatedState so the observer invokes the latest callback without unnecessary re-registration. Direct registration in the composable body can repeat during recomposition and lacks reliable cleanup. Lifecycle events describe owner transitions, not exactly-once human attention.

Scenario and implementation

A diagnostics screen asks its host to refresh a lightweight status indicator when its lifecycle owner starts. This illustrative component requires AndroidX Lifecycle and lifecycle-runtime-compose, where LocalLifecycleOwner is provided. The callback must be fast and nonblocking; it may submit an intent to a ViewModel.

KOTLIN
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.compose.LocalLifecycleOwner
​
@Composable
fun DiagnosticStatus(
    label: String,
    onOwnerStarted: () -> Unit,
    lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current
) {
    val latestOnStarted by rememberUpdatedState(onOwnerStarted)
    DisposableEffect(lifecycleOwner) {
        val observer = LifecycleEventObserver { _, event ->
            if (event == Lifecycle.Event.ON_START) {
                latestOnStarted()
            }
        }
        lifecycleOwner.lifecycle.addObserver(observer)
        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }
    Text(label)
}

Replacing the owner removes the observer from the old owner before setting up the new registration. Updating only the callback keeps that registration and changes what it calls. Registration can receive lifecycle catch-up events when the owner is already started; do not assume every callback corresponds to a new navigation visit. Composition lifetime and owner lifecycle are distinct. Effect cleanup and callback capture, Lifecycle event observers.

Check and tradeoff

With a controllable lifecycle owner, transition to STARTED, update the callback, stop/start again, and verify only the new callback runs. Replace the owner and dispose the component; events from the previous owner must no longer notify the host. A subscription API that returns a cancellation handle follows the same acquire/release pattern. Suspending, lifecycle-gated stream collection belongs in lifecycle-aware coroutine APIs rather than a blocking observer callback.

AND-35 — Answer

Short answer: Use derivedStateOf when an observed value changes often but the UI decision based on it changes less often. A scroll position can change continuously while a button only needs to appear after one threshold. Remembering an initializer alone does not make a calculated value follow later state changes.

Detailed explanation:

remember retains a value or object; it does not independently observe changes inside an initializer. derivedStateOf can make a rapidly changing scroll position produce a less frequently changing Boolean. Use it for the button's threshold, then measure frame timing and the affected composition scopes. It has its own cost and is unnecessary when the derived result changes as often as its inputs.

Scenario and implementation

An inventory search displays thousands of descriptions, but the shortcut needs only “first item visible or not.” This illustrative Compose/Material 3 component assumes the supplied row labels are display text; list positions are appropriate here because there is no per-row state or stable domain identity in this small example.

KOTLIN
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch
​
@Composable
fun InventoryResults(labels: List<String>) {
    val listState = rememberLazyListState()
    val scope = rememberCoroutineScope()
    val showShortcut by remember(listState) {
        derivedStateOf { listState.firstVisibleItemIndex > 0 }
    }
    Box(Modifier.fillMaxSize()) {
        LazyColumn(state = listState, modifier = Modifier.fillMaxSize()) {
            items(labels) { label ->
                Text(label, modifier = Modifier.padding(16.dp))
            }
        }
        if (showShortcut) {
            Button(
                onClick = { scope.launch { listState.animateScrollToItem(0) } },
                modifier = Modifier.align(Alignment.BottomEnd).padding(16.dp)
            ) {
                Text("Back to first result")
            }
        }
    }
}

remember { listState.firstVisibleItemIndex > 0 } would cache a snapshot instead of the intended observation. Using the raw index as a remember key still observes each index change at that call site. Derived state is useful when many source changes leave the consumed result equal; it cannot prevent unrelated state reads from invalidating their own scopes. Derived-state use and cost, Compose performance phases.

Check and tradeoff

Scroll through several rows and confirm the button appears only after leaving item zero and disappears after returning. Check frame timing on representative hardware, including button appearance and animation, instead of declaring success from a lower recomposition count alone. A cheap "$first $last" string usually needs a direct expression; caching or derived state adds machinery without reducing meaningful updates when every input change changes the output.

AND-36 — Answer

Short answer: Start the work from the click handler using a coroutine scope owned by that part of the composition. The scope is cancelled when its call site leaves composition, matching a temporary snackbar interaction. Define whether another tap queues, replaces, or ignores the previous request instead of leaving the behavior accidental.

Detailed explanation:

Launch event-triggered snackbar work from rememberCoroutineScope inside the click handler. That scope is cancelled when its call site leaves composition. LaunchedEffect(key) instead describes work whose lifetime follows composition and a changing key. Explicitly choose how repeated taps behave; screen-owned feedback must not own a business operation that needs longer survival.

Scenario and implementation

An offline help action displays an explanation without saving data. This illustrative Material 3 component cancels its previous snackbar request on another tap, so pending feedback does not accumulate.

KOTLIN
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
​
@Composable
fun OfflineHelp() {
    val scope = rememberCoroutineScope()
    val snackbar = remember { SnackbarHostState() }
    var feedbackJob by remember { mutableStateOf<Job?>(null) }
    Scaffold(snackbarHost = { SnackbarHost(snackbar) }) { padding ->
        Button(
            onClick = {
                feedbackJob?.cancel()
                feedbackJob = scope.launch {
                    snackbar.showSnackbar("Offline edits sync when connected.")
                }
            },
            modifier = Modifier.padding(padding)
        ) {
            Text("Explain offline mode")
        }
    }
}

A click handler is already the event boundary; launching during composition could repeat work as the UI is recomposed. For a timer tied to the currently displayed banner, LaunchedEffect(bannerId) can express restart/cancellation when the banner changes. For an upload, save the operation durably and give an appropriate worker/repository responsibility; a longer scope alone does not provide persistence. Composition-owned event scopes, snackbar suspension and cancellation.

Check and tradeoff

Tap repeatedly and confirm feedback does not build a queue, then navigate away while it is displayed and confirm this component's request is cancelled. Recompose due to an unrelated theme or label change and verify no new request starts. Cancelling older feedback is a deliberate UX choice; a queue can be appropriate for distinct user-visible messages, but it needs bounded delivery and clear ownership.

AND-37 — Answer

Short answer: Ask when the user chooses scanning, explain the need when appropriate, and respect the result. Keep manual entry available if permission is denied. Check permission again before using the camera because permission can change; a missing rationale alone does not prove that the denial is permanent.

Detailed explanation:

Check permission when the user chooses scanning, explain the need when a rationale is appropriate, and launch RequestPermission from that action. Handle denial without blocking manual entry. Permission can change outside the screen, so check it again before protected API use. A false rationale result is ambiguous: it can occur before the first request or when further dialogs are suppressed.

Scenario and implementation

A receipt flow can always accept a manually entered amount. This illustrative component assumes an Android runtime-permission environment (API 23+), AndroidX Activity Compose, Core, and Material 3. Its Activity host is injected explicitly. The app supplies onScanAllowed and onManualEntry; the scanner must handle revocation or SecurityException at the actual camera boundary. Production strings belong in localized resources.

Add the permission and optional hardware declaration inside the existing manifest:

XML
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera.any" android:required="false" />
KOTLIN
import android.Manifest
import android.content.pm.PackageManager
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
​
@Composable
fun ReceiptInputActions(
    activity: ComponentActivity,
    onScanAllowed: () -> Unit,
    onManualEntry: () -> Unit
) {
    val latestScan by rememberUpdatedState(onScanAllowed)
    var showRationale by remember { mutableStateOf(false) }
    var requestPending by remember { mutableStateOf(false) }
    var message by remember { mutableStateOf<String?>(null) }
    val permission = Manifest.permission.CAMERA
    val launcher = rememberLauncherForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { granted ->
        requestPending = false
        if (granted) {
            message = null
            latestScan()
        } else {
            message = "Camera access declined. Manual entry is still available."
        }
    }
    Column {
        Button(
            enabled = !requestPending && !showRationale,
            onClick = {
                when {
                    ContextCompat.checkSelfPermission(activity, permission) ==
                        PackageManager.PERMISSION_GRANTED -> latestScan()
                    ActivityCompat.shouldShowRequestPermissionRationale(
                        activity, permission
                    ) -> showRationale = true
                    else -> {
                        requestPending = true
                        launcher.launch(permission)
                    }
                }
            }
        ) { Text("Scan receipt") }
        TextButton(onClick = onManualEntry) { Text("Enter receipt manually") }
        message?.let { Text(it) }
    }
    if (showRationale) {
        AlertDialog(
            onDismissRequest = { showRationale = false },
            title = { Text("Allow receipt scanning?") },
            text = { Text("The camera reads your receipt. You can enter it manually instead.") },
            confirmButton = {
                TextButton(onClick = {
                    showRationale = false
                    requestPending = true
                    launcher.launch(permission)
                }) { Text("Continue") }
            },
            dismissButton = {
                TextButton(onClick = { showRationale = false }) { Text("Not now") }
            }
        )
    }
}

Do not request from the composable body or automatically re-prompt after denial. If the system no longer presents a dialog, explain that manual entry works and that the user can change permission in system settings; avoid claiming a request counter can identify every platform state. Optional camera hardware also requires a capability check before offering scanning. Runtime-permission request flow, permission activity-result contract.

Check and tradeoff

Exercise first grant, denial, rationale cancellation, repeated denial, activity recreation during a request, and permission revocation in settings. Re-enter scanning and verify a current permission check occurs. Confirm manual entry remains reachable with TalkBack and large text. The component keeps only transient dialog feedback locally; a retained permission result must never become the authority for later camera access.

AND-38 — Answer

Short answer: DiffUtil needs stable old and new snapshots to find what changed. Mutating a row already held by the old snapshot can make both snapshots show the same new value, hiding the edit. Submit new list and item values, compare stable item IDs separately from displayed content, and avoid stale captured positions.

Detailed explanation:

Diffing requires old and new snapshots that remain unchanged during comparison. Mutating a submitted row can make both snapshots describe the new value, so the change disappears. Compare stable IDs for identity and rendered fields for content; submit a new list with replacement immutable rows. Keep the latest list in its owner rather than reconstructing edits from an adapter snapshot that may still be awaiting a diff.

Scenario and implementation

A warehouse operator renames shipments while background updates reorder the list. This illustrative Android Views example requires AndroidX RecyclerView. Each row is a small immutable value; the main-thread owner accepts complete updates and local rename intents. Server conflict policy remains a repository concern.

KOTLIN
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
​
data class ShipmentRow(val id: String, val title: String, val status: String)
​
class ShipmentAdapter(private val onOpen: (String) -> Unit) :
    ListAdapter<ShipmentRow, ShipmentAdapter.Holder>(RowDiff) {
​
    class Holder(val label: TextView) : RecyclerView.ViewHolder(label)
​
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
        val label = TextView(parent.context).apply {
            layoutParams = RecyclerView.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            val inset = (16 * resources.displayMetrics.density).toInt()
            setPadding(inset, inset, inset, inset)
            isFocusable = true
        }
        return Holder(label)
    }
​
    override fun onBindViewHolder(holder: Holder, position: Int) {
        val row = getItem(position)
        holder.label.text = "${row.title}: ${row.status}"
        holder.label.setOnClickListener { onOpen(row.id) }
    }
​
    private object RowDiff : DiffUtil.ItemCallback<ShipmentRow>() {
        override fun areItemsTheSame(old: ShipmentRow, new: ShipmentRow) =
            old.id == new.id
​
        override fun areContentsTheSame(old: ShipmentRow, new: ShipmentRow) =
            old == new
    }
}
​
class ShipmentRowsOwner(private val adapter: ShipmentAdapter) {
    private var rows: List<ShipmentRow> = emptyList()
​
    fun replace(newRows: List<ShipmentRow>) {
        require(newRows.map { it.id }.distinct().size == newRows.size)
        rows = newRows.toList()
        adapter.submitList(rows)
    }
​
    fun rename(id: String, title: String) {
        require(title.isNotBlank())
        rows = rows.map { if (it.id == id) it.copy(title = title) else it }
        adapter.submitList(rows)
    }
}

The click listener captures the row's stable ID at binding, not a position that may move before the click. RecyclerView stable-ID mode is a separate optional mechanism and is not enabled by defining areItemsTheSame. toList() isolates the outer list; nested mutable objects would still require immutable modeling or a suitable deep snapshot. Marshal owner calls to main. ListAdapter submission contract, identity and rendered-content comparisons.

Check and tradeoff

Submit A/B, rename A, then reorder B/A and click both visible rows; verify labels and opened IDs. Submit two renames rapidly and check the last owner state eventually appears without reviving the first edit. An intermediate diff may be superseded, so do not use every submission's commit callback as a required business acknowledgement. Payload updates can reduce rebinding work, but only after a correct full bind and measurements show that complexity is useful.

AND-39 — Answer

Short answer: The outer vertical scroller can give its child unlimited height, but a vertical lazy list needs a finite viewport to decide which rows to compose. A single LazyColumn containing the header, rows, and footer gives that scrolling region one owner. Deliberately bounded or cross-axis nested scrollers can still be valid.

Detailed explanation:

A vertically scrolling parent can measure its child with unbounded height, but a vertical lazy list needs a finite viewport. Put the header, transactions, and footer in one LazyColumn so one container owns that scrolling region. Nesting is not universally invalid: a deliberately fixed-height inner list or a scrollable child on a different axis can be appropriate when the interaction is intentional.

Scenario and implementation

A statement screen adds a total above its transaction list. This illustrative Compose/Material 3 component assumes a finite screen-sized parent and unique stable row IDs. Amounts are already formatted display values; accounting arithmetic belongs in the domain layer.

KOTLIN
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
​
data class StatementRow(val id: String, val description: String, val amount: String)
​
@Composable
fun StatementScreen(totalLabel: String, rows: List<StatementRow>) {
    LazyColumn(modifier = Modifier.fillMaxSize()) {
        item(key = "statement-header") {
            Text("Statement: $totalLabel", Modifier.padding(16.dp))
        }
        items(rows, key = { "transaction:${it.id}" }) { row ->
            Text("${row.description}: ${row.amount}", Modifier.padding(16.dp))
        }
        item(key = "statement-footer") {
            Text("End of statement", Modifier.padding(16.dp))
        }
    }
}

Prefixing transaction keys keeps them distinct from the header/footer keys. Arbitrarily large fixed heights merely conceal the measurement problem and can defeat lazy rendering. A truly bounded child, such as a 200-dp independent picker, has a viewport but still needs a sensible nested scrolling and accessibility experience. A horizontal carousel within a vertical list is a different-axis design and is commonly useful. Lazy-list nesting constraints and alternatives.

Check and tradeoff

Use empty, single-row, and long data sets at narrow widths and large font scale. Scroll to both ends and confirm header, rows, and footer remain reachable without a measurement exception. Verify TalkBack traversal follows the intended document order. Combining regions into one lazy container simplifies scrolling; separate bounded panes can be suitable on large displays, where each pane has a clear independent purpose.

AND-40 — Answer

Short answer: Give the content one clear owner for the space reserved by system bars and app bars. Apply Scaffold content padding once, then mark those insets as consumed for descendants. Padding moves content; consuming insets records that an ancestor handled them, preventing children from adding the same space again.

Detailed explanation:

Use Scaffold's content padding once for the list and tell descendants that those insets have been consumed. Applying padding moves content; consuming insets records that an ancestor handled that space and does not itself move content. Repeating system-bar padding around already handled Material 3 components can add gaps, while ignoring the supplied padding can cover important content.

Scenario and implementation

An inbox draws its background edge to edge while keeping the first message below the toolbar and the last one reachable above system navigation. This illustrative Material 3 component assumes an edge-to-edge Activity host. It uses TopAppBar with the explicit opt-in required by Material 3 versions where that API is experimental; pin and verify the project's actual dependency versions.

KOTLIN
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
​
data class InboxRow(val id: String, val subject: String)
​
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun InsetAwareInbox(rows: List<InboxRow>) {
    Scaffold(topBar = { TopAppBar(title = { Text("Inbox") }) }) { innerPadding ->
        LazyColumn(
            modifier = Modifier.fillMaxSize().consumeWindowInsets(innerPadding),
            contentPadding = innerPadding
        ) {
            items(rows, key = { it.id }) { row ->
                Text(row.subject, Modifier.padding(16.dp))
            }
        }
    }
}

contentPadding insets the scrollable content, allowing the list's viewport/background to occupy its intended region. consumeWindowInsets prevents cooperating descendants from applying those same inset portions again. The 16-dp row padding is design spacing, not a guessed status-bar height. Avoid adding another statusBarsPadding/navigationBarsPadding wrapper without a reason. Material 3 inset ownership, inset consumption.

Check and tradeoff

Check portrait/landscape, cutout devices, gesture and three-button navigation, and large text. Scroll the last row fully into reach and inspect the first row beneath the app bar. Test any nested screen host as well, because a parent may already handle insets. A form with an on-screen keyboard needs a deliberate IME policy too; this inbox contains no text input and does not claim to demonstrate keyboard avoidance. Central ownership reduces accidental duplication while leaving individual components free to add ordinary design spacing.

Key Takeaways

  • Encapsulation protects invariants and ownership; val, private setters, and collection interfaces each provide narrower guarantees.
  • A thread-safe API does not automatically make a multi-step operation atomic. Main-thread confinement does not prevent stale asynchronous results.
  • Coroutine scopes own work, effect keys define Compose lifetimes, and saved state reconstructs UI context rather than persisting every business operation.
  • Durable intent, idempotency, authorization, and recovery cross mobile/backend boundaries. Verify behavior with controlled failure scenarios and production evidence.