Communitygithub.com

Compose Multiplatform 패턴

KMP 프로젝트에서 Compose Multiplatform 및 Jetpack Compose를 위한 상태 관리, 탐색, 테마, 성능, 플랫폼별 UI 패턴입니다. Compose 또는 Jetpack Compose UI, 상태, 탐색, 테마를 구축할 때 사용합니다.

Compose Multiplatform 패턴란 무엇인가요?

이 스킬은 Compose Multiplatform과 Jetpack Compose를 사용하여 Android, iOS, Desktop, Web에서 공유 UI를 구축하기 위한 포괄적인 패턴 모음을 제공합니다. 주요 영역으로는 ViewModel과 단일 상태 객체, Event Sink 패턴을 통한 상태 관리, Compose Navigation 2.8 이상의 type-safe 탐색, 슬롯 기반 API와 Modifier 순서를 포함한 Composable 설계, expect/actual을 활용한 KMP 플랫폼별 UI, @Stable/@Immutable 애노테이션, key() 사용, derivedStateOf 활용, 재구성 중 할당 회피 등 성능 최적화 기법, Material 3 동적 테마 적용 등을 다룹니다. 또한 mutableStateOf 대신 MutableStateFlow 사용, NavController를 Composable에 깊이 전달하지 않기, Composable 함수 내에서 무거운 연산 피하기 등 일반적인 안티 패턴을 지적하여 개발자가 성능과 유지보수성이 뛰어난 Compose UI를 작성할 수 있도록 돕습니다. 이 패턴은 Cursor, Codex, Claude Code 등 Compose Multiplatform을 지원하는 모든 도구에서 활용할 수 있습니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/compose-multiplatform-patterns

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

Compose Multiplatform 패턴은(는) 무엇을 하나요?

Compose Multiplatform과 Jetpack Compose를 사용하여 Android, iOS, Desktop, Web에서 공유 UI를 구축하기 위한 패턴입니다. 상태 관리, 탐색, 테마, 성능을 다룹니다.

활성화 시점

  • Compose UI( Jetpack Compose 또는 Compose Multiplatform) 구축 시
  • ViewModel 및 Compose 상태로 UI 상태 관리 시
  • KMP 또는 Android 프로젝트에서 탐색 구현 시
  • 재사용 가능한 Composable 및 디자인 시스템 설계 시
  • 재구성 및 렌더링 성능 최적화 시

상태 관리

ViewModel + 단일 상태 객체

화면 상태에 단일 데이터 클래스를 사용합니다. StateFlow로 노출하고 Compose에서 수집합니다:

data class ItemListState(
    val items: List<Item> = emptyList(),
    val isLoading: Boolean = false,
    val error: String? = null,
    val searchQuery: String = ""
)

class ItemListViewModel(
    private val getItems: GetItemsUseCase
) : ViewModel() {
    private val _state = MutableStateFlow(ItemListState())
    val state: StateFlow<ItemListState> = _state.asStateFlow()

    fun onSearch(query: String) {
        _state.update { it.copy(searchQuery = query) }
        loadItems(query)
    }

    private fun loadItems(query: String) {
        viewModelScope.launch {
            _state.update { it.copy(isLoading = true) }
            getItems(query).fold(
                onSuccess = { items -> _state.update { it.copy(items = items, isLoading = false) } },
                onFailure = { e -> _state.update { it.copy(error = e.message, isLoading = false) } }
            )
        }
    }
}

Compose에서 상태 수집

@Composable
fun ItemListScreen(viewModel: ItemListViewModel = koinViewModel()) {
    val state by viewModel.state.collectAsStateWithLifecycle()

    ItemListContent(
        state = state,
        onSearch = viewModel::onSearch
    )
}

@Composable
private fun ItemListContent(
    state: ItemListState,
    onSearch: (String) -> Unit
) {
    // Stateless Composable — 미리보기 및 테스트가 용이
}

이벤트 싱크 패턴

복잡한 화면의 경우 여러 콜백 람다 대신 봉인된 인터페이스를 이벤트에 사용합니다:

sealed interface ItemListEvent {
    data class Search(val query: String) : ItemListEvent
    data class Delete(val itemId: String) : ItemListEvent
    data object Refresh : ItemListEvent
}

// ViewModel 내
fun onEvent(event: ItemListEvent) {
    when (event) {
        is ItemListEvent.Search -> onSearch(event.query)
        is ItemListEvent.Delete -> deleteItem(event.itemId)
        is ItemListEvent.Refresh -> loadItems(_state.value.searchQuery)
    }
}

// Composable 내 — 여러 람다 대신 단일 람다
ItemListContent(
    state = state,
    onEvent = viewModel::onEvent
)

탐색

Type-Safe 탐색 (Compose Navigation 2.8+)

@Serializable 객체로 경로를 정의합니다:

@Serializable data object HomeRoute
@Serializable data class DetailRoute(val id: String)
@Serializable data object SettingsRoute

@Composable
fun AppNavHost(navController: NavHostController = rememberNavController()) {
    NavHost(navController, startDestination = HomeRoute) {
        composable<HomeRoute> {
            HomeScreen(onNavigateToDetail = { id -> navController.navigate(DetailRoute(id)) })
        }
        composable<DetailRoute> { backStackEntry ->
            val route = backStackEntry.toRoute<DetailRoute>()
            DetailScreen(id = route.id)
        }
        composable<SettingsRoute> { SettingsScreen() }
    }
}

다이얼로그 및 바텀 시트 탐색

명령형 show/hide 대신 dialog() 및 오버레이 패턴을 사용합니다:

NavHost(navController, startDestination = HomeRoute) {
    composable<HomeRoute> { /* ... */ }
    dialog<ConfirmDeleteRoute> { backStackEntry ->
        val route = backStackEntry.toRoute<ConfirmDeleteRoute>()
        ConfirmDeleteDialog(
            itemId = route.itemId,
            onConfirm = { navController.popBackStack() },
            onDismiss = { navController.popBackStack() }
        )
    }
}

Composable 설계

슬롯 기반 API

유연성을 위해 슬롯 매개변수로 Composable을 설계합니다:

@Composable
fun AppCard(
    modifier: Modifier = Modifier,
    header: @Composable () -> Unit = {},
    content: @Composable ColumnScope.() -> Unit,
    actions: @Composable RowScope.() -> Unit = {}
) {
    Card(modifier = modifier) {
        Column {
            header()
            Column(content = content)
            Row(horizontalArrangement = Arrangement.End, content = actions)
        }
    }
}

Modifier 순서

Modifier 순서는 중요합니다 — 다음 순서로 적용합니다:

Text(
    text = "Hello",
    modifier = Modifier
        .padding(16.dp)          // 1. 레이아웃 (패딩, 크기)
        .clip(RoundedCornerShape(8.dp))  // 2. 모양
        .background(Color.White) // 3. 그리기 (배경, 테두리)
        .clickable { }           // 4. 상호작용
)

KMP 플랫폼별 UI

플랫폼 Composable을 위한 expect/actual

// commonMain
@Composable
expect fun PlatformStatusBar(darkIcons: Boolean)

// androidMain
@Composable
actual fun PlatformStatusBar(darkIcons: Boolean) {
    val systemUiController = rememberSystemUiController()
    SideEffect { systemUiController.setStatusBarColor(Color.Transparent, darkIcons) }
}

// iosMain
@Composable
actual fun PlatformStatusBar(darkIcons: Boolean) {
    // iOS는 UIKit interop 또는 Info.plist를 통해 처리
}

성능

건너뛸 수 있는 재구성을 위한 안정적인 타입

모든 속성이 안정적일 때 클래스를 @Stable 또는 @Immutable로 표시합니다:

@Immutable
data class ItemUiModel(
    val id: String,
    val title: String,
    val description: String,
    val progress: Float
)

key() 및 Lazy 목록 올바르게 사용

LazyColumn {
    items(
        items = items,
        key = { it.id }  // 안정적인 키는 항목 재사용 및 애니메이션 활성화
    ) { item ->
        ItemRow(item = item)
    }
}

derivedStateOf로 읽기 지연

val listState = rememberLazyListState()
val showScrollToTop by remember {
    derivedStateOf { listState.firstVisibleItemIndex > 5 }
}

재구성 중 할당 방지

// 나쁨 — 매 재구성마다 새 람다와 목록 생성
items.filter { it.isActive }.forEach { ActiveItem(it, onClick = { handle(it) }) }

// 좋음 — 각 항목에 키를 지정하여 콜백이 올바른 행에 연결됨
val activeItems = remember(items) { items.filter { it.isActive } }
activeItems.forEach { item ->
    key(item.id) {
        ActiveItem(item, onClick = { handle(item) })
    }
}

테마

Material 3 동적 테마

@Composable
fun AppTheme(
    darkTheme: Boolean = isSystemInDarkTheme(),
    dynamicColor: Boolean = true,
    content: @Composable () -> Unit
) {
    val colorScheme = when {
        dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
            if (darkTheme) dynamicDarkColorScheme(LocalContext.current)
            else dynamicLightColorScheme(LocalContext.current)
        }
        darkTheme -> darkColorScheme()
        else -> lightColorScheme()
    }

    MaterialTheme(colorScheme = colorScheme, content = content)
}

피해야 할 안티 패턴

  • ViewModel에서 mutableStateOf 사용 — MutableStateFlow와 collectAsStateWithLifecycle이 수명 주기에 더 안전합니다.
  • Composable 깊숙이 NavController 전달 — 대신 람다 콜백을 전달합니다.
  • @Composable 함수 내에서 무거운 연산 — ViewModel 또는 remember {}로 이동합니다.
  • ViewModel 초기화 대신 LaunchedEffect(Unit) 사용 — 일부 설정에서 구성 변경 시 재실행됩니다.
  • Composable 매개변수에서 새 객체 인스턴스 생성 — 불필요한 재구성을 유발합니다.

참고 자료

모듈 구조 및 계층화는 스킬 android-clean-architecture를 참조하세요. 코루틴 및 Flow 패턴은 스킬 kotlin-coroutines-flows를 참조하세요.

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

관련 스킬