kotlin-concurrency-and-flow
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseKotlin concurrency and Flow
Kotlin并发与Flow
Core principle
核心原则
Give asynchronous work an explicit owner and lifetime, then model durable state
and transient events with primitives whose delivery and replay semantics match
the product contract.
为异步工作明确指定所有者和生命周期,然后使用交付与重放语义符合产品契约的原语来建模持久状态和瞬时事件。
Procedure
步骤
- Identify each coroutine owner, cancellation boundary, producer, consumer, durable state, and transient event.
- Select a scope whose lifecycle owns the work; do not retain arbitrary scopes or hide unstructured launches behind non-suspending APIs.
- Model renderable, current data as state and imperative one-shot work as an event only when its loss and replay behavior are explicitly acceptable.
- Choose Flow sharing and buffering semantics from the producer and consumer lifetimes rather than from a default.
- Read the focused reference for the material concern below.
- Finish when cancellation, restart, replay, and failure behavior are all observable from the public API and no caller must guess who owns the work.
- 识别每个协程的所有者、取消边界、生产者、消费者、持久状态和瞬时事件。
- 选择一个生命周期能管控工作的作用域;不要保留任意作用域,也不要在非挂起式API背后隐藏非结构化启动。
- 仅当损失和重放行为明确可接受时,才将可渲染的当前数据建模为状态,将命令式一次性工作建模为事件。
- 根据生产者和消费者的生命周期选择Flow的共享与缓冲语义,而非使用默认值。
- 阅读下方相关主题的聚焦参考文档。
- 当取消、重启、重放和失败行为都能从公共API中观察到,且调用者无需猜测谁拥有工作时,即完成任务。
Topic router
主题导航
| Signal | Read |
|---|---|
Stored | Structured concurrency |
| Flow state and events |
| Compose collection or UI effect handling | Compose state and effects |
| 信号 | 阅读内容 |
|---|---|
存储的 | 结构化并发 |
| Flow状态与事件 |
| Compose收集或UI效果处理 | Compose状态与效果 |
RED/GREEN agent scenarios
RED/GREEN代理场景
- RED stores a long-lived in a service and launches from arbitrary callers. GREEN makes ownership and cancellation follow a defined lifecycle boundary.
CoroutineScope - Novel case: a screen needs replayable loading state and non-replayable navigation. GREEN uses distinct state and event contracts with documented delivery semantics.
- Counterexample: a suspend function already has a caller-owned scope. GREEN does not add an internal scope merely to make the API look asynchronous.
- RED场景:在服务中存储一个长生命周期的,并从任意调用者处启动协程。GREEN场景:让所有权和取消机制遵循定义好的生命周期边界。
CoroutineScope - 新案例:某个页面需要可重放的加载状态和不可重放的导航逻辑。GREEN场景:使用具有明确交付语义的不同状态和事件契约。
- 反例:一个挂起函数已有调用者所属的作用域。GREEN场景:不会仅仅为了让API看起来是异步的而添加内部作用域。