agentleFS
lennonpetricklennonpetrick/android-engineering-skills/android-patterns/SKILL.md

android-patterns

Skill40 starsChanged 27 days agoMITView on GitHub

Defines all implementation patterns for Android features: Unidirectional Data Flow (UDF), ViewModel design, Flow composition, error handling, repository pattern, domain UseCases, and Compose UI patterns. Use this skill whenever implementing a ViewModel, designing state or action models, writing a repository or UseCase, composing Flows, handling errors, building Compose screens or components, or reviewing code for correctness of reactive patterns or state management.

1 other project uses a version of this.

Adopted by

Most recently taken up by

  • Other versions1 project uses a version of this.

    Word for word · 0

    None found.

    Edited · 0

    None found.

    Wrote their own version · 1

    1. raditia/CraftKit★ 1same name

    How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.

  • In this repository2 other files it gives its agents.

The file

Show its rules and text

We split this skill into the rules it gives an agent

46 rules. About 0 are common, 39 are distinctive, and 7 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈39

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 7

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Use this skill to implement Android features with explicit state, reactive flows, and testable logic.

    line 9
  2. Distinctive:

    Use a single direction of data movement.

    line 13
  3. Distinctive:

    Use explicit state types instead of boolean flags when possible.

    line 33
  4. Distinctive:

    Use a sealed interface for high-level screen lifecycle state.

    line 37
  5. Distinctive:

    Use a data class for the rendered content.

    line 50
  6. Distinctive:

    Use a sealed interface for user intents.

    line 63
  7. Distinctive:

    Use a sealed interface for one-time side effects.

    line 75
  8. Distinctive:

    Keep actions raw and user driven.

    line 86
  9. Distinctive:

    Keep UiState focused on rendering.

    line 88
  10. Distinctive:

    Keep internal state separate from UiState whenever the ViewModel needs raw typed values.

    line 89
  11. Very specific:

    Use stateIn for StateFlow exposure.

    line 145
  12. Very specific:

    Prefer SharingStarted.WhileSubscribed(...) for UI-bound streams.

    line 146
  13. Very specific:

    Keep onAction(action) as the single entry point for user input.

    line 147
  14. Distinctive:

    Use private helpers for large branches.

    line 148
  15. Distinctive:

    Keep mutable state private.

    line 149
  16. Distinctive:

    Use Flow operators to compose asynchronous work.

    line 153
  17. Distinctive:

    Use when output depends on multiple latest values.

    line 157
  18. Distinctive:

    Use when a new upstream value should cancel previous work.

    line 167
  19. Distinctive:

    Use for pure transformations.

    line 177
  20. Distinctive:

    Use when the next value depends on the previous one.

    line 185
  21. Distinctive:

    Use to prevent unnecessary recomputation and re-rendering.

    line 195
  22. Distinctive:

    Use to share upstream work and keep the latest state available.

    line 199
  23. Distinctive:

    Prefer reactive composition over manual callbacks.

    line 203
  24. Distinctive:

    Avoid creating duplicate subscriptions for the same source.

    line 204
  25. Very specific:

    Use mapLatest or flatMapLatest when newer input should cancel older work.

    line 206
  26. Distinctive:

    Use explicit domain errors when possible.

    line 210
  27. Very specific:

    Prefer Result<T> for operations that may fail.

    line 224
  28. Distinctive:

    Do not throw exceptions through flow pipelines when a recoverable result model is enough.

    line 225
  29. Distinctive:

    Keep one-time UI errors in events, not in durable state, unless the UI must render them persistently.

    line 228
  30. Distinctive:

    Keep mapping explicit and dedicated to mapper classes.

    line 260
  31. Distinctive:

    Use cases represent application actions.

    line 264
  32. Very specific:

    Use fun verb. For example, fetchItemsUseCase.fetch() or observeItemsUseCase.observe()

    line 274
  33. Distinctive:

    Keep use cases small and focused.

    line 275
  34. Distinctive:

    Use use cases to preserve a stable boundary between presentation and domain.

    line 276
  35. Distinctive:

    Put reusable business logic behind use cases or domain services.

    line 277
  36. Distinctive:

    Use a screen composable to connect to the ViewModel, and a stateless content composable for rendering.

    line 283
  37. Distinctive:

    Do not pass ViewModel into deeply nested UI components.

    line 300
  38. Distinctive:

    Always create preview for composable components and content composable when possible.

    line 301
  39. Distinctive:

    Keep purely visual or temporary state in Compose when it does not belong in the ViewModel.

    line 309
  40. Distinctive:

    Always provide stable keys in lazy lists when item identity exists.

    line 324
  41. Very specific:

    Use a local TextFieldValue only when the UI must preserve cursor position or selection.

    line 328
  42. Distinctive:

    Use a visual transformation only for display formatting.

    line 330
  43. Distinctive:

    Keep mapping and calculations out of composables.

    line 334
  44. Distinctive:

    Use dedicated classes for:

    line 336
  45. Distinctive:

    Do not mix these concerns in one place unless the feature is extremely small.

    line 350
  46. Distinctive:

    Check the code against these questions:

    line 354

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Android Patterns

Use this skill to implement Android features with explicit state, reactive flows, and testable logic.

1. Unidirectional Data Flow

Use a single direction of data movement.

User action -> ViewModel -> state update -> UI render -> optional event

Rules:

  • Composables do not own business state.
  • Composables emit actions upward through callbacks.
  • ViewModels own screen behavior and coordinate the data flow.
  • State flows down from the ViewModel into Compose.
  • Events flow out through one-shot streams such as SharedFlow.

Prefer this structure:

UiAction -> onAction() -> internal state -> derived state -> UiState -> Composable

2. State model design

Use explicit state types instead of boolean flags when possible.

Screen state

Use a sealed interface for high-level screen lifecycle state.

@Immutable
internal sealed interface FeatureScreenUiState {
    data object Loading : FeatureScreenUiState
    data class Loaded(val data: FeatureUiState) : FeatureScreenUiState
    data object Error : FeatureScreenUiState
}

Content state

Use a data class for the rendered content.

@Immutable
internal data class FeatureUiState(
    val title: String,
    val subtitle: String,
    val items: List<ItemUiState>,
)

Actions

Use a sealed interface for user intents.

@Immutable
internal sealed interface FeatureUiAction {
    data object Retry : FeatureUiAction
    data class QueryChanged(val value: String) : FeatureUiAction
}

Events

Use a sealed interface for one-time side effects.

internal sealed interface FeatureUiEvent {
    data class ShowError(val message: String) : FeatureUiEvent
    data object NavigateBack : FeatureUiEvent
}

Rules:

  • Keep actions raw and user driven.
  • Keep events transient.
  • Keep UiState focused on rendering.
  • Keep internal state separate from UiState whenever the ViewModel needs raw typed values.

3. ViewModel pattern

ViewModels should coordinate, not calculate everything.

Responsibilities:

  • receive actions
  • update internal state
  • connect domain flows
  • expose StateFlow
  • emit one-time events
  • orchestrate loading, retry, and recovery behavior

ViewModels should not:

  • parse API responses
  • contain complex business rules
  • format display values
  • leak DTOs or Retrofit types
  • make UI rendering decisions that belong in Compose

Recommended shape:

@HiltViewModel
internal class FeatureViewModel @Inject constructor(
    private val observeItemsUseCase: ObserveItemsUseCase,
    private val mapper: FeatureUiStateMapper,
) : ViewModel() {

    private val _internalState = MutableStateFlow<FeatureInput?>(null)
    private val _uiEvents = MutableSharedFlow<FeatureUiEvent>()
    val uiEvents: SharedFlow<FeatureUiEvent> = _uiEvents.asSharedFlow()

    val uiState: StateFlow<FeatureScreenUiState> =
        someFlow
            .map { result -> result.fold(...) }
            .stateIn(
                scope = viewModelScope,
                started = SharingStarted.WhileSubscribed(5_000),
                initialValue = FeatureScreenUiState.Loading,
            )

    fun onAction(action: FeatureUiAction) {
        when (action) {
            FeatureUiAction.Retry -> retry()
            is FeatureUiAction.QueryChanged -> updateQuery(action.value)
        }
    }
}

Rules:

  • Use stateIn for StateFlow exposure.
  • Prefer SharingStarted.WhileSubscribed(...) for UI-bound streams.
  • Keep onAction(action) as the single entry point for user input.
  • Use private helpers for large branches.
  • Keep mutable state private.

4. Flow composition patterns

Use Flow operators to compose asynchronous work.

combine

Use when output depends on multiple latest values.

combine(firstFlow, secondFlow) { first, second ->
    ...
}

flatMapLatest

Use when a new upstream value should cancel previous work.

queryFlow.flatMapLatest { query ->
    repository.search(query)
}

map

Use for pure transformations.

flow.map { value -> transform(value) }

scan

Use when the next value depends on the previous one.

flow.scan(initialValue) { previous, current ->
    ...
}

distinctUntilChanged

Use to prevent unnecessary recomputation and re-rendering.

shareIn and stateIn

Use to share upstream work and keep the latest state available.

Rules:

  • Prefer reactive composition over manual callbacks.
  • Avoid creating duplicate subscriptions for the same source.
  • Derive new flows from existing flows instead of copying state by hand.
  • Use mapLatest or flatMapLatest when newer input should cancel older work.

5. Error handling

Use explicit domain errors when possible.

Prefer:

sealed interface FeatureError {
    data object Network : FeatureError
    data object Unauthorized : FeatureError
    data object Unknown : FeatureError
}

Rules:

  • Prefer Result<T> for operations that may fail.
  • Do not throw exceptions through flow pipelines when a recoverable result model is enough.
  • Map low-level errors into domain or presentation friendly errors.
  • Handle errors near the boundary where they happen.
  • Keep one-time UI errors in events, not in durable state, unless the UI must render them persistently.

Recommended patterns:

  • initial load failure -> Error screen state or explicit error state
  • recoverable refresh failure -> keep last good data and emit a snack bar event
  • unrecoverable failure -> show an error state with retry action

6. Repository pattern

Repositories should expose domain models and flows, not transport models.

Prefer:

  • Flow<Result<List<Model>>>
  • Flow<Result<Model>>
  • suspend functions returning domain models or Result

Avoid:

  • DTOs in repository interfaces
  • Retrofit response types in presentation
  • callbacks for data sources when Flow is a better fit

Repository responsibilities may include:

  • network access
  • local cache access
  • synchronization
  • mapping between layers
  • retry or refresh coordination where appropriate

Keep mapping explicit and dedicated to mapper classes.

7. Use case pattern

Use cases represent application actions.

Naming:

  • FetchItemsUseCase
  • ObserveItemsUseCase
  • SubmitFormUseCase

Rules:

  • Use fun [verb](...). For example, fetchItemsUseCase.fetch() or observeItemsUseCase.observe()
  • Keep use cases small and focused.
  • Use use cases to preserve a stable boundary between presentation and domain.
  • Put reusable business logic behind use cases or domain services.

8. Compose patterns

Screen and content split

Use a screen composable to connect to the ViewModel, and a stateless content composable for rendering.

@Composable
internal fun FeatureScreen(viewModel: FeatureViewModel) {
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    FeatureContent(
        uiState = uiState,
        onAction = viewModel::onAction,
    )
}

Rules:

  • Screen composable owns collection and side effects.
  • Content composable receives state and callbacks only.
  • Do not pass ViewModel into deeply nested UI components.
  • Always create preview for composable components and content composable when possible.

One-shot events

Collect events in LaunchedEffect from the screen layer.

Local UI state

Keep purely visual or temporary state in Compose when it does not belong in the ViewModel.

Examples:

  • bottom sheet visibility
  • text field focus
  • local expanded state
  • transient animations

State hoisting

Hoist state to the nearest composable that needs to share it.

List rendering

Always provide stable keys in lazy lists when item identity exists.

Text input

Use a local TextFieldValue only when the UI must preserve cursor position or selection.

Use a visual transformation only for display formatting. Keep the raw input value separate.

9. Mapping and calculation

Keep mapping and calculations out of composables.

Use dedicated classes for:

  • mappers
  • parsers
  • formatters
  • calculators

Rules:

  • parsing converts text to typed input
  • formatting converts typed values to display values
  • mapping converts model A to model B
  • calculators implement domain rules and state derivation

Do not mix these concerns in one place unless the feature is extremely small.

10. Practical review checklist

Check the code against these questions:

  • Does the ViewModel coordinate rather than compute everything?
  • Are actions, state, and events distinct?
  • Are flows shared and lifecycle aware?
  • Does the UI remain stateless where possible?
  • Are errors handled explicitly?
  • Are mapping and formatting extracted into named classes?
  • Is the reactive behavior easy to explain from the code?

Refactor when:

  • a composable mutates business state
  • a ViewModel directly formats UI strings
  • repository interfaces leak DTOs
  • flow subscriptions are duplicated unnecessarily
  • a feature uses flags where sealed state would be clearer

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.