본문으로 건너뛰기
Skillpedia
일반 코딩48k · #5012

kotlin-coroutines-expert

하는 일

이 가이드는 Kotlin에서 'Coroutines'와 'Flow'를 사용하는 방법을 가르칩니다. 이들은 프로그램을 멈추지 않고 여러 작업을 동시에 수행하기 위한 도구입니다. 작업을 체계적으로 구성하고, 오류를 처리하고, 코드를 테스트하는 방법을 보여 줍니다.

사용하는 경우

  • ✓여러 작업을 동시에 수행해야 하는 Kotlin 프로그램을 만들 때.
  • ✓시간이 지나며 변하는 데이터 스트림을 다룰 때.
  • ✓취소되었거나 실패한 작업을 디버깅할 때.

스킬 링크

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/kotlin-coroutines-expert/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/kotlin-coroutines-expert/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“Kotlin에서 두 개의 네트워크 작업을 동시에 수행하고, 발생할 수 있는 오류를 처리하려면 어떻게 해야 하나요?”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

이 가이드는 '구조화된 동시성(structured concurrency)'이라는 개념을 사용해 작업이 올바르게 관리되도록 합니다. 또 순차적인 데이터를 다루는 'Flow' 사용법과 오류를 체계적으로 관리하는 방법도 배웁니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

Kotlin Coroutines Expert

Overview

A guide to mastering asynchronous programming with Kotlin Coroutines. Covers advanced topics like structured concurrency, Flow transformations, exception handling, and testing strategies.

When to Use This Skill

  • Use when implementing asynchronous operations in Kotlin.
  • Use when designing reactive data streams with Flow.
  • Use when debugging coroutine cancellations or exceptions.
  • Use when writing unit tests for suspending functions or Flows.

Step-by-Step Guide

1. Structured Concurrency

Always launch coroutines within a defined CoroutineScope. Use coroutineScope or supervisorScope to group concurrent tasks.

suspend fun loadDashboardData(): DashboardData = coroutineScope {
    val userDeferred = async { userRepo.getUser() }
    val settingsDeferred = async { settingsRepo.getSettings() }

    DashboardData(
        user = userDeferred.await(),
        settings = settingsDeferred.await()
    )
}

2. Exception Handling

Use CoroutineExceptionHandler for top-level scopes, but rely on try-catch within suspending functions for granular control.

val handler = CoroutineExceptionHandler { _, exception ->
    println("Caught $exception")
}

viewModelScope.launch(handler) {
    try {
        riskyOperation()
    } catch (e: IOException) {
        // Handle network error specifically
    }
}

3. Reactive Streams with Flow

Use StateFlow for state that needs to be retained, and SharedFlow for events.

// Cold Flow (Lazy)
val searchResults: Flow<List<Item>> = searchQuery
    .debounce(300)
    .flatMapLatest { query -> searchRepo.search(query) }
    .flowOn(Dispatchers.IO)

// Hot Flow (State)
val uiState: StateFlow<UiState> = _uiState.asStateFlow()

Examples

Example 1: Parallel Execution with Error Handling

suspend fun fetchDataWithErrorHandling() = supervisorScope {
    val task1 = async {
        try { api.fetchA() } catch (e: CancellationException) { throw e } catch (e: IOException) { null }
    }
    val task2 = async { api.fetchB() }

    // A child failure does not directly cancel its siblings.
    // But an uncaught exception from await escapes the supervisor block and cancels it.
    val result1 = task1.await()
    val result2 = task2.await() // May throw
}

Best Practices

  • ✅ Do: Use Dispatchers.IO for blocking I/O operations.
  • ✅ Do: Cancel scopes when they are no longer needed (e.g., ViewModel.onCleared).
  • ✅ Do: Use TestScope and runTest for unit testing coroutines.
  • ❌ Don't: Use GlobalScope. It breaks structured concurrency and can lead to leaks.
  • ❌ Don't: Catch CancellationException unless you rethrow it.

Troubleshooting

Problem: Coroutine test hangs or fails unpredictably. Solution: Ensure you are using runTest and injecting TestDispatcher into your classes so you can control virtual time.

Limitations

  • Use this skill only when the task clearly matches the scope described above.
  • Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
  • Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.

Examples are fragments: supply imports, repository interfaces, Android lifecycle dependencies and the installed coroutines version. Handle each awaited failure deliberately and rethrow cancellation. SharedFlow replay/buffer choices determine delivery while no collector is active; it is not a guaranteed event queue. StateFlow conflates state changes. Test cancellation and slow/absent collectors, not only happy paths. Official exception behavior.

자주 묻는 질문

'구조화된 동시성'이란 무엇인가요?

동시에 실행되는 작업들을 하나의 그룹처럼 다루어, 통제된 방식으로 시작되고 멈추도록 정리하는 방식입니다.

'StateFlow'와 'SharedFlow'의 차이는 무엇인가요?

'StateFlow'는 검색창의 텍스트처럼 무언가의 현재 상태를 담는 데 쓰입니다. 'SharedFlow'는 버튼 클릭처럼 일어날 수 있는 이벤트를 보내는 데 쓰입니다.

'GlobalScope'를 쓰면 안 되는 이유는 무엇인가요?

'GlobalScope'는 구조화된 동시성을 무시하므로, 작업이 필요 이상으로 계속 실행되어 문제와 메모리 누수를 일으킬 수 있습니다.

상세 정보

작성자의 원본 설명

Expert patterns for Kotlin Coroutines and Flow, covering structured concurrency, error handling, and testing.

repo: sickn33/agentic-awesome-skills

인기도

GitHub 스타
48k
순위
#5012
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬