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가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
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.IOfor blocking I/O operations. - ✅ Do: Cancel scopes when they are no longer needed (e.g.,
ViewModel.onCleared). - ✅ Do: Use
TestScopeandrunTestfor unit testing coroutines. - ❌ Don't: Use
GlobalScope. It breaks structured concurrency and can lead to leaks. - ❌ Don't: Catch
CancellationExceptionunless 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.
인기도
- GitHub 스타
- 48k
- 순위
- #5012
- 라이선스
- MIT
- 업데이트
- 2026. 10. 15.
댓글
- …
이 저장소의 다른 스킬
00-andruia-consultant
48k에이전트가 AI 프로젝트를 시작하거나 개선할 수 있도록 코드를 분석하고 스페인어로 실행 계획을 세워 줍니다.
007
48k에이전트가 보안 감사와 위협 모델링을 수행해 공격과 취약점으로부터 프로젝트를 보호하도록 돕습니다.
10-andruia-skill-smith
48k에이전트가 AI 도구의 작동 방식을 정의하고 문서를 쓰며 구조를 검증하도록 돕습니다.
20-andruia-niche-intelligence
48k에이전트가 신뢰할 수 있는 자료를 바탕으로 특정 산업의 맥락, 규칙, 사용 패턴, 위험을 정리한 요약을 만들도록 돕습니다.