android-coroutines-flow

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Android Coroutines Flow

Android 协程 Flow

When To Use

何时使用

  • Use this skill when the request is about: android flow collection, fix coroutine scope in android, structured concurrency in viewmodel.
  • Primary outcome: Use coroutines, Flow, structured concurrency, dispatchers, and cancellation-safe Android async pipelines.
  • Handoff skills when the scope expands:
  • android-state-management
  • android-workmanager-notifications
  • 当请求涉及以下内容时使用本技能:Android flow 收集、修复Android中的协程作用域、ViewModel中的结构化并发。
  • 核心目标:使用协程、Flow、结构化并发、调度器以及支持安全取消的Android异步管道。
  • 当范围扩大时移交至以下技能:
  • android-state-management
  • android-workmanager-notifications

Workflow

工作流程

  1. Map the request to the current Android stack, module boundaries, and minimum supported API level.
  2. Inspect the existing implementation for implicit assumptions, duplicate helpers, and outdated patterns.
  3. Apply the smallest change that improves correctness, readability, and long-term maintainability.
  4. Validate the result against the relevant showcase app path and repo benchmarks.
  5. Hand off adjacent work to the next specialized skill only after the core foundation is stable.
  1. 将请求映射到当前Android技术栈、模块边界以及最低支持的API级别。
  2. 检查现有实现中是否存在隐式假设、重复辅助工具以及过时模式。
  3. 采用最小改动来提升正确性、可读性以及长期可维护性。
  4. 对照相关演示应用路径和代码仓库基准验证结果。
  5. 仅在核心基础稳定后,将相邻工作移交至下一个专业技能。

Guardrails

护栏准则

  • Prefer official Android and Kotlin guidance over custom local conventions when they conflict.
  • Keep public APIs boring and explicit; avoid clever abstractions that hide Android lifecycle costs.
  • Do not mix architectural cleanup with product behavior changes unless the request explicitly needs both.
  • Document any compatibility constraints that will affect old modules or generated code.
  • 当官方Android和Kotlin指南与本地自定义规范冲突时,优先遵循官方指南。
  • 保持公共API简单明确;避免使用隐藏了Android生命周期开销的巧妙抽象。
  • 不要将架构清理与产品行为变更混合处理,除非请求明确要求同时处理两者。
  • 记录所有会影响旧模块或生成代码的兼容性约束。

Anti-Patterns

反模式

  • Sprinkling helpers across modules without a clear ownership boundary.
  • Introducing framework-specific code into pure domain or data layers.
  • Refactoring every adjacent file when only one contract needed to change.
  • Leaving migration notes implied instead of writing them down.
  • 在没有明确所有权边界的情况下在模块间随意散布辅助工具。
  • 将框架特定代码引入纯领域层或数据层。
  • 仅需要修改一个契约时就重构所有相邻文件。
  • 不明确写下迁移说明,仅依赖隐含信息。

Remediation Examples

修复示例

Inject dispatchers instead of hard-coding them

注入调度器而非硬编码

kotlin
class TaskRepository(
    private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO,
) {
    suspend fun refresh(): List<TaskUiModel> = withContext(ioDispatcher) { loadTasks() }
}
kotlin
class TaskRepository(
    private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO,
) {
    suspend fun refresh(): List<TaskUiModel> = withContext(ioDispatcher) { loadTasks() }
}

Collect flows with lifecycle awareness

具备生命周期感知的Flow收集

kotlin
viewLifecycleOwner.lifecycleScope.launch {
    viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
        viewModel.uiState.collect { render(it) }
    }
}
kotlin
viewLifecycleOwner.lifecycleScope.launch {
    viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
        viewModel.uiState.collect { render(it) }
    }
}

Preserve cancellation in generic error handling

在通用错误处理中保留取消机制

kotlin
try {
    repository.refresh()
} catch (error: CancellationException) {
    throw error
} catch (error: Exception) {
    emit(UiState.Error(error))
}
kotlin
try {
    repository.refresh()
} catch (error: CancellationException) {
    throw error
} catch (error: Exception) {
    emit(UiState.Error(error))
}

Examples

示例

Happy path

正常场景

  • Scenario: Model task updates as StateFlow and shared event channels in the Compose fixture.
  • Command:
    cd examples/orbittasks-compose && ./gradlew :app:testDebugUnitTest
  • 场景:在Compose测试夹具中将任务更新建模为StateFlow和共享事件通道。
  • 命令:
    cd examples/orbittasks-compose && ./gradlew :app:testDebugUnitTest

Edge case

边缘场景

  • Scenario: Recover from cancellation and configuration changes in the XML activity flow.
  • Command:
    cd examples/orbittasks-xml && ./gradlew :app:testDebugUnitTest
  • 场景:在XML Activity流程中从取消和配置变更中恢复。
  • 命令:
    cd examples/orbittasks-xml && ./gradlew :app:testDebugUnitTest

Failure recovery

故障恢复

  • Scenario: Disambiguate coroutine requests from state-management and WorkManager prompts.
  • Command:
    python3 scripts/eval_triggers.py --skill android-coroutines-flow
  • 场景:区分来自状态管理和WorkManager提示的协程请求。
  • 命令:
    python3 scripts/eval_triggers.py --skill android-coroutines-flow

Done Checklist

完成检查清单

  • The implementation path is explicit, minimal, and tied to the right Android surface.
  • Relevant example commands and benchmark prompts have been exercised or updated.
  • Handoffs to adjacent skills are documented when the request crosses boundaries.
  • Official references cover the chosen pattern and the main migration or troubleshooting path.
  • 实现路径明确、最小化,并且适配正确的Android表层。
  • 相关示例命令和基准提示已经过测试或更新。
  • 当请求跨边界时,已记录相邻技能的移交说明。
  • 官方参考资料覆盖了所选模式以及主要的迁移或故障排查路径。

Official References

官方参考