Android compose patterns

From makifbaysal/tasktrooper · View interactive version

Android compose patterns is an AI agent skill from the GitHub repository makifbaysal/tasktrooper. Use when building native Android with Jetpack Compose - stateless composables, state hoisting, ViewModel-owned state, edge-to-edge, predictive back, adaptive layout, atomic components, and Material theming over hardcoded values

How to use this skill

Skill file

Jetpack Compose Patterns

Overview

Native Android (Jetpack Compose) is chosen when a task needs deep Android integration or the app is already native (see native-vs-flutter-decision). Same discipline as Flutter/SwiftUI: small stateless composables, state hoisted out, reusable atomic components.

Core principle: Composables are stateless functions of state. State is hoisted to a ViewModel; composables emit events upward.

Rules

Edge-to-edge (enforced from targetSdk 35)

Predictive back (default at targetSdk 36)

Adaptive layout

Previews and tests across the matrix

Semantics

Worked Example

// ViewModel owns state + logic (unit-testable, no Compose)
class TaskListViewModel(private val repo: TaskRepository) : ViewModel() {
    private val _state = MutableStateFlow<UiState<List<Task>>>(UiState.Loading)
    val state: StateFlow<UiState<List<Task>>> = _state
    fun load() = viewModelScope.launch {
        _state.value = UiState.Loading
        _state.value = try {
            val items = repo.list()
            if (items.isEmpty()) UiState.Empty else UiState.Data(items)
        } catch (e: CancellationException) {
            throw e                              // never swallow cancellation
        } catch (e: Exception) {
            UiState.Error(e)
        }
    }
}

// stateless composable renders state, emits events
@Composable
fun TaskListScreen(state: UiState<List<Task>>, onRetry: () -> Unit) = when (state) {
    is UiState.Loading -> AppSpinner()
    is UiState.Error   -> AppErrorView(message = state.cause.message, onRetry = onRetry)
    is UiState.Data    -> TaskList(tasks = state.value)
    is UiState.Empty   -> EmptyView()
}

The fix from the previous version: runCatching { } wrapped around a suspend call inside viewModelScope.launch catches CancellationException along with real errors, which breaks structured concurrency (a cancelled screen keeps "loading" instead of stopping) — use try/catch and rethrow CancellationException explicitly. The Empty branch is now actually emitted when the list comes back empty, not just declared and never reached.

Testing

Common Mistakes

Red Flags

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.