Architecture, Kotlin, and UI
Scope: Kotlin idioms and null safety, coroutines/Flow/lifecycle/cancellation, working with whatever architecture pattern a project already has, Jetpack Compose and XML Views side by side, state management, accessibility, and resource/error-handling lifecycle.
Never force an architecture or library onto a project that doesn't already use it. If a codebase is MVP with XML Views and no DI framework, review and extend it as MVP/XML/no-DI — don't propose a Compose/MVI/Hilt rewrite unless the user explicitly asked for a migration. Identify and follow the existing pattern before suggesting a different one.
1. Kotlin idioms and null safety
- Prefer non-null types and smart-cast-friendly code over
!!; a!!in new code is a finding unless it's genuinely provably non-null in a way the compiler can't see and that's commented. - Use
sealed class/sealed interfacefor closed sets of states/results rather than a loose set of booleans or an enum carrying no data — this is what makeswhenexhaustive-checkable and makes illegal states unrepresentable. - Data classes for value-holding types; avoid mutable public
varproperties on shared/cached objects where immutability would prevent whole classes of bugs. - Extension functions are idiomatic for adding behavior without inheritance (e.g. mapper functions
fun UserDto.toDomain(): User) — prefer them over utility/static-method classes for this purpose. - Scope functions (
let,run,apply,also,with) should clarify, not obscure — if a chain needs a comment to explain whatit/thisrefers to, prefer a named variable instead.
2. Coroutines, Flow, lifecycle, and cancellation
- Coroutines should be launched from a scope tied to the right lifecycle:
viewModelScopefor ViewModel-owned work,lifecycleScope/repeatOnLifecycle(Lifecycle.State.STARTED)for UI-collecting work in anActivity/Fragment, and structured child scopes for anything else — avoidGlobalScope, which outlives everything and leaks work. Flowcollection in a composable should go throughcollectAsStateWithLifecycle()(lifecycle-aware) rather than plaincollectAsState(), so collection pauses when the UI isn't visible instead of doing background work and holding state for a backgrounded screen.- Cancellation must be cooperative: long-running suspend work should check
ensureActive()/isActiveor use cancellable APIs rather than looping past a cancellation signal; afinallyblock for cleanup should avoid suspending calls that themselves get cancelled (usewithContext(NonCancellable)for cleanup that must complete). - Pick the right hot/cold and sharing primitive for the job:
StateFlowfor observable mutable state with a current value,SharedFlow/Channelfor one-shot events (navigation, snackbars) that shouldn't replay on configuration change — collapsing both into oneStateFlowis a common source of "event fired twice on rotation" bugs. withContext(Dispatchers.IO)for blocking I/O, notDispatchers.Default(CPU-bound work) or the main dispatcher — getting this backwards either blocks the UI or starves the limitedDefaultthread pool.- Prefer a plain
suspend funand let the caller own the scope/lifecycle over calling.launch { }from inside a class that doesn't itself own a scope — launching from aninit {}block, or from a DI-provided singleton with no bound lifecycle, is a common source of coroutines that silently outlive the screen that started them and leak.
3. Architecture patterns — work with what exists
- Identify the pattern actually in use (MVVM, MVI/UDF, MVP, or none-in-particular) by reading a few existing feature modules/packages before writing new code, not by assuming a "modern" default.
- Common MVVM/UDF shape when it is present: a single
UiState(often a sealed type modeling loading/success/error/empty explicitly, rather than four separate booleans) exposed asStateFlow<UiState>from aViewModel, with one-shot effects on a separateChannel/SharedFlow. If the project already does this, match it; if it doesn't, don't retrofit it into an unrelated change. - Layering (UI → domain → data) is a useful default for new, non-trivial features, but match the granularity the project already uses — don't introduce a domain-layer
UseCaseclass for a one-line passthrough if the rest of the codebase doesn't do that, and don't skip a layer the rest of the codebase relies on. - Dependency injection: if the project uses Hilt/Koin/manual DI, extend it the same way; don't introduce a second DI mechanism alongside an existing one, and don't treat either framework as a universal default to migrate toward. If the project already uses Hilt specifically, a few idioms are worth holding to: prefer constructor injection and reserve field injection for framework classes (
Activity/Fragment) Hilt requires it for; use@Bindsover@Providesfor interface-to-implementation bindings (cheaper to generate); reserve@Singletonfor genuinely app-wide, stateful, or expensive-to-create objects rather than a default scope, since over-scoping hides lifecycle bugs and wastes memory; and in tests, prefer constructor-injected fakes over@HiltAndroidTest/@UninstallModulesmachinery except for instrumented tests that specifically need the DI graph wired. The same spirit (constructor injection, deliberate scoping, fakes over mocks in unit tests) applies under Koin too — the annotations differ, the discipline doesn't.
4. Jetpack Compose and XML Views — both are valid
- Many production apps are XML Views only, Compose only, or an interop mix (
ComposeView/AndroidView) — treat whichever is present as the correct baseline for that codebase. - Compose: hoist state to the lowest common stateful ancestor that needs it; keep composables that just render state (
stateless/"dumb" composables) separate from ones that own state, which makes them trivially previewable and testable. Side effects belong inLaunchedEffect/DisposableEffect/SideEffect, scoped with keys that reflect actual dependencies — an effect with the wrong key set either reruns too often or misses updates. A common convention worth recognizing (not imposing) if a project already uses it: a stateful "Route" composable that talks to theViewModeland is the only one exposed outside the feature, calling a stateless "Screen" composable (often markedinternal) that only renders the state it's given — match it where present, since it makes the Screen directly previewable/testable without a ViewModel. - XML Views:
ViewBinding(not rawfindViewById) for null-safety and compile-time checking; avoid deeply nestedViewGrouphierarchies that cost extra measure/layout passes — flatten withConstraintLayoutwhere it reduces nesting depth. - Interop:
ComposeViewinside a View hierarchy andAndroidViewinside Compose are both supported and fine to use incrementally — don't treat interop as a sign something is "not done yet" unless the project's own direction says so. AComposeViewreused outside a singleActivity(e.g. held by aRecyclerView.ViewHolderor aFragment's view) should set an explicitsetViewCompositionStrategy(e.g.DisposeOnViewTreeLifecycleDestroyed) rather than relying on the default, which can leak composition state or dispose too early when the view is recycled.AndroidViewinside aLazyColumn/LazyRowitem is comparatively expensive to inflate/bind per item — fine for a handful of items, but worth a second look if it shows up in every row of a long list. - Adaptive layouts: for a screen that needs to behave differently on a phone vs. a larger/foldable device, prefer deriving breakpoints from
WindowSizeClass(compact/medium/expanded width and height buckets) over hardcodeddpthresholds orBoxWithConstraintsalone — it's the platform-recommended, device-independent way to branch layout decisions (e.g. single-pane vs. two-pane) and keeps the logic testable without an actual foldable/tablet.
5. State management
- A screen's state should be representable by a single source of truth (one
UiStateobject/sealed hierarchy) rather than several independently-updated fields that can drift out of sync with each other. - Loading/error/empty/success should usually be explicit states (sealed class branches), not implicit combinations of nullable fields and booleans — the latter allows invalid combinations (e.g.
isLoading = trueanddata != nullanderror != nullall at once) that the former makes unrepresentable. - Configuration changes (rotation, etc.): state surviving rotation should live in a
ViewModel(survives by default) orrememberSaveablefor Compose-local UI state that needs to survive process death, not in plainremember/aView's instance fields.
6. Accessibility
- Every interactive element needs an accessible label:
contentDescriptiononImageView/Image, or Compose'ssemantics { contentDescription = ... }/Modifier.clearAndSetSemanticsfor custom composables. A purely decorative image should havecontentDescription = null(orimportantForAccessibility = "no") so screen readers skip it instead of reading something meaningless. - Reading order for a screen reader follows layout order by default; when the visual order and the logical reading order genuinely diverge (e.g. an overlaid badge, an end-aligned action placed before its label in code), set an explicit
Modifier.semantics { traversalIndex = ... }/isTraversalGroup = truerather than reordering the actual UI just to fix traversal. For content that changes and should be announced proactively (a live score, a form validation error), useliveRegion = LiveRegionMode.Polite(waits for a pause) orAssertive(interrupts) instead of expecting the user to re-discover the change by navigating back to it. - Before adding non-essential motion, check it against a short gate: does it clarify a state change the user would otherwise miss, would a plain cut actually look broken without it, and does it still hold up if the system's reduced-motion/animator-duration-scale setting is on. Motion that's purely decorative, or that breaks (freezes, jumps) under a shortened/zero animation duration, shouldn't gate correctness — functionality must still work with animations off.
- Touch targets should meet the ~48dp minimum; check custom composables/views with small visual size but a tappable area don't shrink the actual target below that.
- Text should scale with system font size settings (avoid hardcoded
sp-overriding behavior that disables user font scaling) and maintain sufficient contrast — don't hardcode colors that only work in one theme if the app supports light/dark. - Test with TalkBack (or Compose's semantics tree in the Layout Inspector) rather than assuming a label is sufficient — a
contentDescriptionthat's technically present but unhelpful ("image", "button") isn't actually accessible.
7. Error handling and resource lifecycle
- Model expected failure explicitly (a
Result<T>/sealedDataErrorreturn type from repository/use-case layers) rather than relying on exceptions for control flow across layers; reserve exceptions for genuinely exceptional, unrecoverable conditions. - Resources that need explicit cleanup (cursors, streams, listeners,
MediaPlayer, cached bitmaps) should useuse {}/try-finally/lifecycle-aware disposal (DisposableEffectin Compose,onDestroyViewin Fragments) — leaking one of these is a common source of the leaks a profiler later flags. - Network/database errors surfaced to the user should be actionable (what happened, what to do), not a raw exception message or stack trace shown in the UI.
8. Navigation
Whatever navigation mechanism a project uses — Compose Navigation, the Fragment-based Navigation component, or a custom router — a few idioms generalize across all of them:
- Keep the navigation controller/host owned by one place (the top-level
NavHost/Activity) and pass navigation as lambda callbacks down into composables/fragments, rather than threading the controller itself through intermediate layers. This keeps lower-level UI testable without a real navigation graph attached. - Pass only simple identifiers (an ID, a string) through navigation arguments/routes, and resolve the full object in the destination's own
ViewModel(from a repository, keyed by that ID) rather than serializing a large object through the navigation layer — the object can go stale between navigation and the destination rendering, and large navigation payloads are easy to get wrong across process death/state restoration. - Group related destinations into nested graphs as a feature grows, rather than flattening everything into one top-level graph — mirrors the module boundaries from §3 if the project is also multi-module.
Sources
- Kotlin language documentation — kotlinlang.org.
- Kotlin coroutines guide and Flow — kotlinlang.org.
- Android app architecture guidance — developer.android.com.
- Jetpack Compose state and architecture and side effects — developer.android.com.
- Android accessibility guidance — developer.android.com.
- Hilt dependency injection guide — developer.android.com (for the
@Binds/@Provides/scoping facts in §3). - Navigation principles — developer.android.com (for the §8 navigation idioms, generalized across navigation implementations).
ViewCompositionStrategyand Window size classes — developer.android.com (for the §4ComposeViewlifecycle and adaptive-layout facts).- Compose semantics: custom traversal order and live regions — developer.android.com (for the §6
traversalIndex/liveRegionfacts). - Pattern framing (UDF
UiState, sealedDataError) was cross-checked against the scope ofrcosteira79/android-skillsandrinkuniks/android-claude-skill. The Hilt-specific idioms in §3, the Screen/Route convention in §4, and the navigation idioms in §8 were all cross-checked againstRanaNadeemAslam/android-ai-skills'sdependency-injection.mdc,compose-ui.md, andnavigation.mdrespectively, verified against the official docs cited above, and generalized away from that repo's per-file "mandate one library" framing (e.g. "Hilt only," "Compose Navigation only") — structure/idioms referenced, no text copied; seedocs/SOURCE_MAPPING.md. - The §2 "let the caller own the scope" idiom was cross-checked against
rcosteira79/android-skills'kotlin-coroutinesskill. The §4ViewCompositionStrategy/AndroidView-in-lazy-list facts were cross-checked againstandroid/skills'migrate-xml-views-to-jetpack-composeinteroperability references (generalized away from its migration-workflow framing — see the "deliberately excluded scope" note indocs/SOURCE_MAPPING.md) and againstliuyi0808/android-review'scompose-uiskill, which also supplied the §4WindowSizeClassadaptive-layout idiom. The §6 traversal-order/live-region facts and the motion-decision gate were cross-checked againstrcosteira79/android-skills'compose/references/accessibility.mdandwenubey/claude-android-skills'wnb-compose-animationskill respectively, each verified against the official docs above before being written in this project's own words — structure/idioms referenced, no text copied; seedocs/SOURCE_MAPPING.md.