Communitygithub.com

Kotlin 코루틴 & 플로우

Android 및 KMP를 위한 Kotlin 코루틴과 Flow 패턴 — 구조적 동시성, Flow 연산자, StateFlow, 오류 처리 및 테스트. 코루틴이나 Flow 코드를 작성하거나 취소 및 동시성 문제를 디버깅할 때 사용하세요.

Kotlin 코루틴 & 플로우란 무엇인가요?

이 스킬은 Kotlin 코루틴과 Flow를 효과적으로 사용하기 위한 포괄적인 패턴 가이드를 제공합니다. Android 및 Kotlin Multiplatform (KMP) 프로젝트에서 구조적 동시성, Flow 기반 리액티브 스트림, 상태 관리, 오류 처리, 테스트 전략을 다룹니다. 주요 내용으로는 `coroutineScope`와 `supervisorScope`를 활용한 병렬 분해, StateFlow를 통한 UI 상태 관리, SharedFlow를 사용한 일회성 이벤트 처리, `debounce`, `distinctUntilChanged`, `flatMapLatest`, `retryWhen`과 같은 고급 Flow 연산자 패턴이 포함됩니다. 또한 Turbine 라이브러리를 사용한 StateFlow 테스트, TestDispatcher를 활용한 가상 시간 제어, Fake 저장소 구현 등 코루틴 및 Flow를 안정적으로 테스트하는 방법을 구체적으로 설명합니다. GlobalScope 남용, CancellationException 잘못 처리, mutable 컬렉션을 StateFlow에 사용하는 등의 안티패턴을 피하도록 안내하여, 생산성과 코드 품질을 높이는 데 중점을 둡니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/kotlin-coroutines-flows

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

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

문서

Kotlin 코루틴 & 플로우은(는) 무엇을 하나요?

Android 및 Kotlin Multiplatform 프로젝트에서 구조적 동시성, Flow 기반 리액티브 스트림, 코루틴 테스트를 위한 패턴입니다.

활성화 조건

  • 비동기 코드를 Kotlin 코루틴으로 작성할 때
  • Flow, StateFlow, SharedFlow를 리액티브 데이터에 사용할 때
  • 동시 작업(병렬 로딩, 디바운스, 재시도)을 처리할 때
  • 코루틴과 Flow를 테스트할 때
  • 코루틴 스코프와 취소를 관리할 때

구조적 동시성

스코프 계층

Application
  └── viewModelScope (ViewModel)
        └── coroutineScope { } (구조적 자식)
              ├── async { } (동시 작업)
              └── async { } (동시 작업)

항상 구조적 동시성을 사용하고 GlobalScope는 절대 사용하지 마세요:

// 나쁜 예
GlobalScope.launch { fetchData() }

// 좋은 예 — ViewModel 수명 주기에 스코프 지정
viewModelScope.launch { fetchData() }

// 좋은 예 — Composable 수명 주기에 스코프 지정
LaunchedEffect(key) { fetchData() }

병렬 분해

병렬 작업에는 coroutineScope + async를 사용하세요:

suspend fun loadDashboard(): Dashboard = coroutineScope {
    val items = async { itemRepository.getRecent() }
    val stats = async { statsRepository.getToday() }
    val profile = async { userRepository.getCurrent() }
    Dashboard(
        items = items.await(),
        stats = stats.await(),
        profile = profile.await()
    )
}

SupervisorScope

자식 실패가 형제를 취소하지 않아야 할 때는 supervisorScope를 사용하세요:

suspend fun syncAll() = supervisorScope {
    launch { syncItems() }       // 여기서 실패해도 syncStats는 취소되지 않음
    launch { syncStats() }
    launch { syncSettings() }
}

Flow 패턴

Cold Flow — 일회성에서 스트림으로 변환

fun observeItems(): Flow<List<Item>> = flow {
    // 데이터베이스가 변경될 때마다 다시 방출
    itemDao.observeAll()
        .map { entities -> entities.map { it.toDomain() } }
        .collect { emit(it) }
}

UI 상태를 위한 StateFlow

class DashboardViewModel(
    observeProgress: ObserveUserProgressUseCase
) : ViewModel() {
    val progress: StateFlow<UserProgress> = observeProgress()
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5_000),
            initialValue = UserProgress.EMPTY
        )
}

WhileSubscribed(5_000)은 마지막 구독자가 사라진 후 5초 동안 업스트림을 활성 상태로 유지합니다 — 설정 변경 시 재시작 없이 유지됩니다.

여러 Flow 결합

val uiState: StateFlow<HomeState> = combine(
    itemRepository.observeItems(),
    settingsRepository.observeTheme(),
    userRepository.observeProfile()
) { items, theme, profile ->
    HomeState(items = items, theme = theme, profile = profile)
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), HomeState())

Flow 연산자

// 검색 입력 디바운스
searchQuery
    .debounce(300)
    .distinctUntilChanged()
    .flatMapLatest { query -> repository.search(query) }
    .catch { emit(emptyList()) }
    .collect { results -> _state.update { it.copy(results = results) } }

// 지수 백오프를 사용한 재시도
fun fetchWithRetry(): Flow<Data> = flow { emit(api.fetch()) }
    .retryWhen { cause, attempt ->
        if (cause is IOException && attempt < 3) {
            delay(1000L * (1 shl attempt.toInt()))
            true
        } else {
            false
        }
    }

일회성 이벤트를 위한 SharedFlow

class ItemListViewModel : ViewModel() {
    private val _effects = MutableSharedFlow<Effect>()
    val effects: SharedFlow<Effect> = _effects.asSharedFlow()

    sealed interface Effect {
        data class ShowSnackbar(val message: String) : Effect
        data class NavigateTo(val route: String) : Effect
    }

    private fun deleteItem(id: String) {
        viewModelScope.launch {
            repository.delete(id)
            _effects.emit(Effect.ShowSnackbar("항목이 삭제되었습니다"))
        }
    }
}

// Composable에서 수집
LaunchedEffect(Unit) {
    viewModel.effects.collect { effect ->
        when (effect) {
            is Effect.ShowSnackbar -> snackbarHostState.showSnackbar(effect.message)
            is Effect.NavigateTo -> navController.navigate(effect.route)
        }
    }
}

디스패처

// CPU 집약적 작업
withContext(Dispatchers.Default) { parseJson(largePayload) }

// I/O 바운드 작업
withContext(Dispatchers.IO) { database.query() }

// 메인 스레드 (UI) — viewModelScope에서 기본값
withContext(Dispatchers.Main) { updateUi() }

KMP에서는 Dispatchers.Default와 Dispatchers.Main을 사용하세요(모든 플랫폼에서 사용 가능). Dispatchers.IO는 JVM/Android 전용입니다 — 다른 플랫폼에서는 Dispatchers.Default를 사용하거나 DI로 제공하세요.

취소

협력적 취소

장기 실행 루프는 취소를 확인해야 합니다:

suspend fun processItems(items: List<Item>) = coroutineScope {
    for (item in items) {
        ensureActive()  // 취소되면 CancellationException을 던짐
        process(item)
    }
}

try/finally를 사용한 정리

viewModelScope.launch {
    try {
        _state.update { it.copy(isLoading = true) }
        val data = repository.fetch()
        _state.update { it.copy(data = data) }
    } finally {
        _state.update { it.copy(isLoading = false) }  // 취소되어도 항상 실행됨
    }
}

테스트

Turbine으로 StateFlow 테스트

@Test
fun `검색이 항목 목록을 업데이트한다`() = runTest {
    val fakeRepository = FakeItemRepository().apply { emit(testItems) }
    val viewModel = ItemListViewModel(GetItemsUseCase(fakeRepository))

    viewModel.state.test {
        assertEquals(ItemListState(), awaitItem())  // 초기 상태

        viewModel.onSearch("query")
        val loading = awaitItem()
        assertTrue(loading.isLoading)

        val loaded = awaitItem()
        assertFalse(loaded.isLoading)
        assertEquals(1, loaded.items.size)
    }
}

TestDispatcher로 테스트

@Test
fun `병렬 로드가 올바르게 완료된다`() = runTest {
    val viewModel = DashboardViewModel(
        itemRepo = FakeItemRepo(),
        statsRepo = FakeStatsRepo()
    )

    viewModel.load()
    advanceUntilIdle()

    val state = viewModel.state.value
    assertNotNull(state.items)
    assertNotNull(state.stats)
}

Flow 페이킹

class FakeItemRepository : ItemRepository {
    private val _items = MutableStateFlow<List<Item>>(emptyList())

    override fun observeItems(): Flow<List<Item>> = _items

    fun emit(items: List<Item>) { _items.value = items }

    override suspend fun getItemsByCategory(category: String): Result<List<Item>> {
        return Result.success(_items.value.filter { it.category == category })
    }
}

피해야 할 안티패턴

  • GlobalScope 사용 — 코루틴 누수, 구조적 취소 불가
  • 스코프 없이 init {}에서 Flow 수집 — viewModelScope.launch 사용
  • 가변 컬렉션과 함께 MutableStateFlow 사용 — 항상 불변 복사본 사용: _state.update { it.copy(list = it.list + newItem) }
  • CancellationException 캐치 — 적절한 취소를 위해 전파시켜야 함
  • 수집을 위해 flowOn(Dispatchers.Main) 사용 — 수집 디스패처는 호출자의 디스패처임
  • @Composable에서 remember 없이 Flow 생성 — 매 재구성마다 Flow를 다시 생성함

참고

Flow의 UI 소비에 대해서는 compose-multiplatform-patterns 스킬을 참조하세요. 코루틴이 계층에 어떻게 맞는지에 대해서는 android-clean-architecture 스킬을 참조하세요.

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/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

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.

관련 스킬