1. 启动操作符
1.1. collect启动流并处理值
lifecycleScope.launch {
flow.collect { value ->
// 处理值
}
}
1.2. launchIn在指定作用域中异步启动流
flow.onEach { updateUI(it) }
.launchIn(viewModelScope)
2. 共享操作符
2.1. stateIn转换为状态流
flow.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000), // 5秒保活
initialValue = null
)
2.2. shareIn转换为共享流
flow.shareIn(
scope = coroutineScope,
started = SharingStarted.WhileSubscribed,
replay = 1 // 新订阅者接收最近1个值
)
3. 单次取值操作符
3.1. first取首个值
val result = flow.first() // 对空流抛出NoSuchElementException
3.2. firstOrNull取首个值或null
val result = flow.firstOrNull() // 对空流安全
3.3. toList/toSet 收集全部值并转换为集合
4. 聚合操作符
4.1. fold带初始值的累积计算
val sum = flow.fold(0) { acc, value -> acc + value }
4.2. reduce无初始值累积
val sum = flowOf(1, 2, 3, 4).reduce { accumulator, value ->
accumulator + value // 累积求和 (结果为10)
}
5. 转换与组合操作符
5.1. transform转换值
flowOf(1, 2).transform { emit(it * 2); emit(it + 1) } // 输出:2, 3, 4, 5
5.2. flatMapMerge合并、转换并展平
flowOf(1, 2).flatMapMerge { flowOf(it, it * 2) }
5.3. flatMapLatest转换并展平最新流(取消前序未完成转换)
flowOf(1, 2).flatMapLatest { flowOf(it, it * 2) }
5.4. combine合并多个流的最新值
flow1.combine(flow2) { a, b -> "a-b" }
6. 时间处理操作符
6.1. debounce防抖
flow { emit(1); delay(100); emit(2) }.debounce(200)
6.2. sample定时采样最新值
flow { while(true) emit("弹幕") }.sample(1000)
7. 错误处理与资源管理
7.1. retryWhen条件重试
.retryWhen { cause, attempt -> attempt < 3 && cause is IOException }
7.2. cancellable响应协程取消
flow { ... }.cancellable()
8. Android扩展
8.1. flowWithLifecycle绑定生命周期的流
// implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.6.0")
flow.flowWithLifecycle(lifecycle, Lifecycle.State.STARTED)
.collect { ... }
8.2. repeatOnLifecycle根据生命周期自动取消或重启协程
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.uiState.collect { ... }
}
}