Flow 进阶:13. 流的上下文 (Flow Context)

本篇解析 example-flow-13.kt。探讨 Flow 在默认情况下运行在哪个线程。

1. 核心准则:上下文保存 (Context Preservation)

Flow 的收集始终发生在调用末端操作符的协程上下文中。

规则解析:

  • 如果你在 runBlocking 中调用 collect,那么 Flow 构建器 (flow { ... }) 里的代码就会运行在 runBlocking 的线程中。
  • 这种特性被称为“上下文保存”。

2. 代码解析

1
2
3
4
5
6
7
8
fun simple(): Flow<Int> = flow {
log("Started simple flow") // [main]
for (i in 1..3) { emit(i) }
}

fun main() = runBlocking {
simple().collect { value -> log("Collected $value") } // [main]
}

3. 开发者感悟

这种设计非常安全且易于理解。作为 API 的提供者,你不需要关心调用者在哪个线程运行;作为调用者,你完全控制了数据的消费线程。

,