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。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 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让你的智能体创建某个特定行业的摘要。它有助于借助可靠的信息来源,了解项目的背景、规则、使用模式和风险。