帮助开发者掌握 Kotlin 协程与 Flow 在 Android 和 KMP 中的实战模式。
复制安装指令,让 AI 自动完成配置 · 推荐新手
请帮我安装 askskill 上的 "kotlin-coroutines-flows" 技能: 1. 下载 https://raw.githubusercontent.com/affaan-m/ECC/main/skills/kotlin-coroutines-flows/SKILL.md 2. 保存为 ~/.claude/skills/kotlin-coroutines-flows/SKILL.md 3. 装好后重载技能,告诉我可以用了
请用 Kotlin 为 Android ViewModel 设计一个基于 StateFlow 的 UI 状态管理方案,包含加载、成功、失败三种状态,并展示如何在 Fragment 或 Compose 中收集状态。
返回一套 ViewModel、UI 状态 sealed class/数据类,以及界面层收集 StateFlow 的示例代码与说明。
我有一个 Kotlin Flow 数据流需要做搜索防抖、去重、切换最新请求和错误处理。请给出使用 debounce、distinctUntilChanged、flatMapLatest、catch 的完整示例,并解释适用场景。
输出一个包含常用 Flow 操作符的完整示例,并说明每个操作符在异步数据流中的作用与组合方式。
请帮我为 Kotlin 协程和 Flow 代码编写单元测试,使用 kotlinx-coroutines-test 验证挂起函数、StateFlow 更新和异常处理逻辑,给出可运行示例。
提供基于测试调度器的单元测试示例,覆盖协程执行、Flow 收集结果与异常断言。
Patterns for structured concurrency, Flow-based reactive streams, and coroutine testing in Android and Kotlin Multiplatform projects.
Application
└── viewModelScope (ViewModel)
└── coroutineScope { } (structured child)
├── async { } (concurrent task)
└── async { } (concurrent task)
Always use structured concurrency — never GlobalScope:
// BAD
GlobalScope.launch { fetchData() }
// GOOD — scoped to ViewModel lifecycle
viewModelScope.launch { fetchData() }
// GOOD — scoped to composable lifecycle
LaunchedEffect(key) { fetchData() }
Use coroutineScope + async for parallel work:
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()
)
}
Use supervisorScope when child failures should not cancel siblings:
suspend fun syncAll() = supervisorScope {
launch { syncItems() } // failure here won't cancel syncStats
launch { syncStats() }
launch { syncSettings() }
}
fun observeItems(): Flow<List<Item>> = flow {
// Re-emits whenever the database changes
itemDao.observeAll()
.map { entities -> entities.map { it.toDomain() } }
.collect { emit(it) }
}
class DashboardViewModel(
observeProgress: ObserveUserProgressUseCase
) : ViewModel() {
val progress: StateFlow<UserProgress> = observeProgress()
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = UserProgress.EMPTY
)
}
WhileSubscribed(5_000) keeps the upstream active for 5 seconds after the last subscriber leaves — survives configuration changes without restarting.
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())
// Debounce search input
searchQuery
.debounce(300)
.distinctUntilChanged()
.flatMapLatest { query -> repository.search(query) }
.catch { emit(emptyList()) }
.collect { results -> _state.update { it.copy(results = results) } }
// Retry with exponential backoff
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
}
}
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("Item deleted"))
}
}
}
…
帮助开发者为代码代理配置性能优化、安全防护与研究优先工作流。
提供数据库迁移、回滚与零停机发布的最佳实践指导,适用于多种 ORM 与 SQL 数据库。
通过双评审智能体对结果进行对抗式校验,提升输出发布前的可靠性
帮助你掌握地道 Rust 模式、所有权与并发实践,编写安全高性能应用。
基于 C++ Core Guidelines 编写、审查并重构更安全现代的 C++ 代码。
为 Claude Code 会话提供系统化校验流程,帮助检查结果正确性与质量。
帮助开发者掌握 Android 与 KMP 中 Kotlin 协程和 Flow 的核心模式与测试方法
提供地道 Kotlin 模式与最佳实践,帮助构建健壮高效且易维护的应用。
帮助开发者用 Kotest、MockK 与协程测试构建高质量 Kotlin 测试体系。
提供地道 Kotlin 设计模式与最佳实践,帮助构建健壮高效且易维护的应用
帮助开发者掌握 KMP 中 Compose Multiplatform 的状态、导航、主题与性能模式。
提供 Kotlin 测试模式与 TDD 实践,涵盖 MockK、协程测试、性质测试和覆盖率分析。