kotlin-coroutines-flows
How to Install
Claude Code:
git clone --depth 1 https://github.com/affaan-m/ECC.git && cp ECC/docs/zh-CN/skills/kotlin-coroutines-flows ~/.claude/skills/kotlin-coroutines-flows -r---
name: kotlin-coroutines-flows
description: Kotlin协程与Flow在Android和KMP中的模式——结构化并发、Flow操作符、StateFlow、错误处理和测试。
origin: ECC
---
# Kotlin 协程与 Flow
适用于 Android 和 Kotlin 多平台项目的结构化并发模式、基于 Flow 的响应式流以及协程测试。
## 何时启用
* 使用 Kotlin 协程编写异步代码
* 使用 Flow、StateFlow 或 SharedFlow 实现响应式数据
* 处理并发操作(并行加载、防抖、重试)
* 测试协程和 Flow
* 管理协程作用域与取消
## 结构化并发
### 作用域层级
```
Application
└── viewModelScope (ViewModel)
└── coroutineScope { } (结构化子作用域)
├── async { } (并发任务)
└── async { } (并发任务)
```
始终使用结构化并发——绝不使用 `GlobalScope`:
```kotlin
// BAD
GlobalScope.launch { fetchData() }
// GOOD — scoped to ViewModel lifecycle
viewModelScope.launch { fetchData() }
// GOOD — scoped to composable lifecycle
LaunchedEffect(key) { fetchData() }
```
### 并行分解
使用 `coroutineScope` + `async` 处理并行工作:
```kotlin
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`:
```kotlin
suspend fun syncAll() = supervisorScope {
launch { syncItems() } // failure here won't cancel syncStats
launch { syncStats() }
launch { syncSettings() }
}
```
## Flow 模式
### Cold Flow —— 一次性操作到流的转换
```kotlin
fun observeItems(): Flow
- > = flow {
// Re-emits whenever the database changes
itemDao.observeAll()
.map { entities -> entities.map { it.toDomain() } }
.collect { emit(it) }
}
```
### 用于 UI 状态的 StateFlow
```kotlin
class DashboardViewModel(
observeProgress: ObserveUserProgressUseCase
) : ViewModel() {
val progress: StateFlow
- ) = coroutineScope {
for (item in items) {
ensureActive() // throws CancellationException if cancelled
process(item)
}
}
```
### 使用 try/finally 进行清理
```kotlin
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) } // always runs, even on cancellation
}
}
```
## 测试
### 使用 Turbine 测试 StateFlow
```kotlin
@Test
fun `search updates item list`() = runTest {
val fakeRepository = FakeItemRepository().apply { emit(testItems) }
val viewModel = ItemListViewModel(GetItemsUseCase(fakeRepository))
viewModel.state.test {
assertEquals(ItemListState(), awaitItem()) // initial
viewModel.onSearch("query")
val loading = awaitItem()
assertTrue(loading.isLoading)
val loaded = awaitItem()
assertFalse(loaded.isLoading)
assertEquals(1, loaded.items.size)
}
}
```
### 使用 TestDispatcher 测试
```kotlin
@Test
fun `parallel load completes correctly`() = runTest {
val viewModel = DashboardViewModel(
itemRepo = FakeItemRepo(),
statsRepo = FakeStatsRepo()
)
viewModel.load()
advanceUntilIdle()
val state = viewModel.state.value
assertNotNull(state.items)
assertNotNull(state.stats)
}
```
### 模拟 Flow
```kotlin
class FakeItemRepository : ItemRepository {
private val _items = MutableStateFlow
- >(emptyList())
override fun observeItems(): Flow
- ) { _items.value = items }
override suspend fun getItemsByCategory(category: String): Result
- > {
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` 中创建 `Flow` 而不使用 `remember`——每次重组都会重新创建 Flow
## 参考
关于 Flow 在 UI 层的消费,请参阅技能:`compose-multiplatform-patterns`。
关于协程在各层中的适用位置,请参阅技能:`android-clean-architecture`。
- > = _items
fun emit(items: List
- ) { _items.value = items }
override suspend fun getItemsByCategory(category: String): Result
Details
| Category | AI/ML → prompt |
| Source | affaan-m/ECC |
| SKILL.md | View on GitHub → |
| Repo Stars | ★ 220.5K |
| Est. per Skill | N/A (shared across 121 skills from this repo) |
| Difficulty | Intermediate |
| Risk Level | Safe |
Related Skills
claude-archive-search
--- name: claude-archive-search description: Use when searching your own past conversations, memory,
bmad-init
--- name: bmad-init description: "Initialize BMad project configuration and load config variables. U
bmad-shard-doc
--- name: bmad-shard-doc description: 'Splits large markdown documents into smaller, organized files
skill-creator
--- name: skill-creator description: Create new skills, modify and improve existing skills, and meas
Works Well With
Skills from the same repository — often designed to work together
accessibility
Accessibility (WCAG 2.2) This skill ensures that digital interfaces are Perceivable, Operable, Under
agent-architecture-audit
Agent Architecture Audit A diagnostic workflow for agent systems that hide failures behind wrapper l
agent-eval
Agent Eval Skill A lightweight CLI tool for comparing coding agents head-to-head on reproducible tas