01-architecture.md
.codex/skills/compose-kotlin-agent-skills/references/01-architecture.md
1# Architecture — Clean Architecture + MVVM + MVI23## Contents45- Clean Architecture layers6- MVVM vs MVI — when to use which7- UiState sealed classes8- ViewModel + StateFlow + UiEvent + UiEffect9- UseCases — when to use, when NOT to use10- Module structure for large apps11- Anti-patterns1213## Clean Architecture Layers1415```16┌─────────────────────────────────────────────┐17│ presentation/ (UI + ViewModel) │18│ ├── Composables render state │19│ ├── ViewModel transforms domain → UiState │20│ └── Depends on: domain │21├─────────────────────────────────────────────┤22│ domain/ (Pure Kotlin — no Android) │23│ ├── Models (data classes) │24│ ├── Repository interfaces │25│ ├── UseCases (optional) │26│ └── Depends on: nothing │27├─────────────────────────────────────────────┤28│ data/ (Implementation) │29│ ├── Repository implementations │30│ ├── Room entities + DAOs │31│ ├── Network DTOs + API services │32│ ├── Mappers (DTO ↔ domain, Entity ↔ domain)│33│ └── Depends on: domain │34└─────────────────────────────────────────────┘35```3637**The dependency rule:** outer layers depend on inner layers. Domain knows nothing about Room, Retrofit, or Compose. Data implements domain interfaces. Presentation consumes domain models.3839## MVVM vs MVI — Decision Guide4041| Aspect | MVVM | MVI |42|--------|------|-----|43| **State** | Multiple StateFlows | Single UiState sealed class |44| **Events** | Direct function calls | Sealed UiEvent dispatched |45| **Complexity** | Lower for simple screens | Higher, but predictable |46| **Debugging** | Harder — multiple state sources | Easier — single state timeline |47| **Use when** | Settings, forms, simple CRUD | Complex screens, multi-step flows |48| **Real example** | Authenticator's `AuthViewModel` | Workout flow with setup → camera → result |4950**Rule of thumb:** start MVVM. Switch to MVI when you have 3+ interdependent state fields or multi-step flows.5152## MVVM — Production Pattern5354From Authenticator app — real ViewModel with search + CRUD:5556```kotlin57data class AccountsUiState(58 val accounts: List<AuthAccount> = emptyList(),59 val searchQuery: String = "",60 val isLoading: Boolean = false,61 val error: String? = null62)6364class AuthViewModel(private val repository: AuthRepository) : ViewModel() {65 private val _searchQuery = MutableStateFlow("")6667 val uiState: StateFlow<AccountsUiState> = combine(68 repository.getAllAccounts(),69 _searchQuery70 ) { accounts, query ->71 val filtered = if (query.isBlank()) accounts72 else accounts.filter {73 it.serviceName.contains(query, ignoreCase = true) ||74 it.accountName.contains(query, ignoreCase = true)75 }76 AccountsUiState(accounts = filtered, searchQuery = query)77 }.stateIn(78 scope = viewModelScope,79 started = SharingStarted.WhileSubscribed(5_000),80 initialValue = AccountsUiState(isLoading = true)81 )8283 fun onSearchQueryChanged(query: String) {84 _searchQuery.value = query85 }8687 fun onAddAccount(account: AuthAccount) {88 viewModelScope.launch {89 repository.insertAccount(account)90 }91 }9293 fun onDeleteAccount(id: String) {94 viewModelScope.launch {95 repository.deleteAccountById(id)96 }97 }98}99```100101**Key decisions:**102- `combine` merges two flows into single UiState — Room auto-emits on DB change103- `SharingStarted.WhileSubscribed(5_000)` — keeps flow active 5s after last subscriber (survives config change)104- No `Dispatchers.IO` — Room already switches threads internally105- Search is reactive — no manual "refresh" needed106107### Screen Consumption108109```kotlin110@Composable111fun AccountsScreen(viewModel: AuthViewModel = koinViewModel()) {112 val state by viewModel.uiState.collectAsStateWithLifecycle()113114 AccountsContent(115 accounts = state.accounts,116 searchQuery = state.searchQuery,117 onSearchChanged = viewModel::onSearchQueryChanged,118 onDelete = viewModel::onDeleteAccount,119 onAdd = viewModel::onAddAccount120 )121}122123@Composable124private fun AccountsContent(125 accounts: List<AuthAccount>,126 searchQuery: String,127 onSearchChanged: (String) -> Unit,128 onDelete: (String) -> Unit,129 onAdd: (AuthAccount) -> Unit130) {131 // Pure UI — no ViewModel reference, fully previewable132 Column {133 SearchBar(query = searchQuery, onQueryChange = onSearchChanged)134 LazyColumn {135 items(accounts, key = { it.id }) { account ->136 AccountCard(account = account, onDelete = { onDelete(account.id) })137 }138 }139 }140}141```142143**Pattern:** Container composable (has ViewModel) → Content composable (stateless, previewable). Content never touches ViewModel directly.144145## MVI — Full Pattern146147For complex screens with multi-step flows:148149```kotlin150// State151data class WorkoutUiState(152 val phase: WorkoutPhase = WorkoutPhase.Setup,153 val workoutType: WorkoutType = WorkoutType.Pushups,154 val repCount: Int = 0,155 val targetReps: Int = 15,156 val timeRemaining: Duration = 3.minutes,157 val isLoading: Boolean = false,158 val error: WorkoutError? = null159)160161enum class WorkoutPhase { Setup, Active, Completed, Failed }162163// Events — user actions164sealed interface WorkoutEvent {165 data class SelectType(val type: WorkoutType) : WorkoutEvent166 data object StartWorkout : WorkoutEvent167 data object PauseWorkout : WorkoutEvent168 data class RepDetected(val count: Int) : WorkoutEvent169 data object Retry : WorkoutEvent170}171172// Effects — one-shot side effects (navigation, snackbar, haptic)173sealed interface WorkoutEffect {174 data object NavigateToResults : WorkoutEffect175 data class ShowError(val message: String) : WorkoutEffect176 data object PlaySuccessHaptic : WorkoutEffect177}178179class WorkoutViewModel(180 private val workoutManager: WorkoutSessionManager,181 private val historyRepo: WorkoutHistoryRepository182) : ViewModel() {183184 private val _state = MutableStateFlow(WorkoutUiState())185 val state: StateFlow<WorkoutUiState> = _state.asStateFlow()186187 private val _effects = Channel<WorkoutEffect>(Channel.BUFFERED)188 val effects: Flow<WorkoutEffect> = _effects.receiveAsFlow()189190 fun onEvent(event: WorkoutEvent) {191 when (event) {192 is WorkoutEvent.SelectType -> {193 _state.update { it.copy(workoutType = event.type) }194 }195 is WorkoutEvent.StartWorkout -> startWorkout()196 is WorkoutEvent.PauseWorkout -> pauseWorkout()197 is WorkoutEvent.RepDetected -> onRepDetected(event.count)198 is WorkoutEvent.Retry -> retry()199 }200 }201202 private fun onRepDetected(count: Int) {203 _state.update { it.copy(repCount = count) }204 if (count >= _state.value.targetReps) {205 _state.update { it.copy(phase = WorkoutPhase.Completed) }206 viewModelScope.launch {207 historyRepo.saveWorkout(/* ... */)208 _effects.send(WorkoutEffect.PlaySuccessHaptic)209 _effects.send(WorkoutEffect.NavigateToResults)210 }211 }212 }213214 // ...215}216```217218### Collecting Effects in Composable219220```kotlin221@Composable222fun WorkoutScreen(viewModel: WorkoutViewModel) {223 val state by viewModel.state.collectAsStateWithLifecycle()224225 // Effects — one-shot, not state226 LaunchedEffect(Unit) {227 viewModel.effects.collect { effect ->228 when (effect) {229 is WorkoutEffect.NavigateToResults -> navController.navigate("results")230 is WorkoutEffect.ShowError -> snackbarHostState.showSnackbar(effect.message)231 is WorkoutEffect.PlaySuccessHaptic -> Haptics.success(context)232 }233 }234 }235236 WorkoutContent(237 state = state,238 onEvent = viewModel::onEvent239 )240}241```242243**Why Channel for effects, not SharedFlow?** Channel guarantees delivery exactly once. SharedFlow with `replay = 0` drops events if no collector is active (e.g., during config change).244245## UseCases — When to Use, When NOT to Use246247### Use When:248- Business logic shared by 2+ ViewModels249- Complex orchestration (multiple repos, validation, transformation)250- Logic needs unit testing independent of ViewModel251252```kotlin253class GenerateTotpCodeUseCase(254 private val accountRepo: AuthRepository,255 private val totpGenerator: TOTPGenerator256) {257 suspend operator fun invoke(accountId: String): Result<String> {258 val account = accountRepo.getAccountById(accountId)259 ?: return Result.failure(AccountNotFound(accountId))260 return Result.success(totpGenerator.generate(account.secretKey))261 }262}263```264265### Skip When:266- Simple pass-through to repository (ViewModel can call repo directly)267- Logic used by only one ViewModel268- Adds indirection without adding value269270```kotlin271// BAD — UseCase that's just a proxy272class GetAllAccountsUseCase(private val repo: AuthRepository) {273 operator fun invoke(): Flow<List<AuthAccount>> = repo.getAllAccounts()274}275276// Just call the repo directly in ViewModel277class AuthViewModel(private val repo: AuthRepository) : ViewModel() {278 val accounts = repo.getAllAccounts()279}280```281282**Rule:** if UseCase body is a single line delegating to one repo, delete it.283284## Module Structure for Large Apps285286```287app/ # Application module — wires everything288├── build.gradle.kts289├── src/main/290│ ├── AndroidManifest.xml291│ └── kotlin/.../292│ ├── App.kt # @HiltAndroidApp or manual DI293│ └── MainActivity.kt294295core/296├── core-ui/ # Design system, shared composables, theme297│ └── DesignSystem.kt, AppColors.kt, Spacing.kt298├── core-domain/ # Shared domain models, base UseCase299│ └── DomainError.kt, BaseUseCase.kt300├── core-data/ # Shared data utilities, network client301│ └── NetworkClient.kt, BaseRepository.kt302└── core-testing/ # Test utilities, fakes, rules303 └── TestDispatcherRule.kt, FakeRepository.kt304305feature/306├── feature-auth/307│ ├── data/ # AuthRepository impl, DTO mappers308│ ├── domain/ # AuthAccount model, AuthRepository interface309│ └── presentation/ # AuthViewModel, AuthScreen310├── feature-workout/311│ ├── data/312│ ├── domain/313│ └── presentation/314└── feature-settings/315 ├── data/316 ├── domain/317 └── presentation/318```319320**Module dependency rules:**321- `feature-*` depends on `core-*` only — never on other features322- `core-domain` depends on nothing (pure Kotlin)323- `core-data` depends on `core-domain`324- `app` depends on all features (wiring only)325- Feature-to-feature communication via shared `core-domain` interfaces or Navigation args326327## Anti-Patterns328329### God ViewModel330```kotlin331// BAD — 800-line ViewModel handling everything332class MainViewModel : ViewModel() {333 val accounts = ...334 val settings = ...335 val workoutState = ...336 val notifications = ...337 fun onLogin() { }338 fun onStartWorkout() { }339 fun onUpdateSettings() { }340}341```342343One ViewModel per screen/feature. If ViewModel exceeds ~200 lines, extract UseCases or split screen.344345### Domain Model = Entity = DTO346```kotlin347// BAD — Room annotations leak into domain348@Entity(tableName = "accounts")349data class AuthAccount(350 @PrimaryKey val id: String,351 @ColumnInfo(name = "service_name") val serviceName: String,352 val secretKey: String // domain shouldn't know about DB columns353)354```355356```kotlin357// RIGHT — separate models with mappers358// domain/359data class AuthAccount(val id: String, val serviceName: String, val secretKey: String)360361// data/362@Entity(tableName = "accounts")363data class AuthAccountEntity(364 @PrimaryKey val id: String,365 @ColumnInfo(name = "service_name") val serviceName: String,366 @ColumnInfo(name = "secret_key") val secretKey: String367)368369fun AuthAccountEntity.toDomain() = AuthAccount(id, serviceName, secretKey)370fun AuthAccount.toEntity() = AuthAccountEntity(id, serviceName, secretKey)371```372373Trade-off: for small apps with no network layer, single model is acceptable. Split when you have DTO + Entity + Domain or when Room annotations would leak into shared KMP modules.374375### Exposing MutableStateFlow376377```kotlin378// BAD — UI can mutate state directly379class AuthViewModel : ViewModel() {380 val state = MutableStateFlow(AccountsUiState())381}382383// RIGHT — private mutable, public read-only384class AuthViewModel : ViewModel() {385 private val _state = MutableStateFlow(AccountsUiState())386 val state: StateFlow<AccountsUiState> = _state.asStateFlow()387}388```389390Always expose `StateFlow`, never `MutableStateFlow`. State changes happen through ViewModel functions only.391