Kotlin流操作符简介

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 { ... }    }}
相关推荐
Monkey-旭3 小时前
Android Bitmap 完全指南:从基础到高级优化
android·java·人工智能·计算机视觉·kotlin·位图·bitmap
Monkey-旭20 小时前
深入理解 Kotlin Flow:异步数据流处理的艺术
android·开发语言·kotlin·响应式编程·flow
程序员江同学2 天前
Kotlin 技术月报 | 2025 年 7 月
android·kotlin
_frank2222 天前
kotlin使用mybatis plus lambdaQuery报错
开发语言·kotlin·mybatis
Bryce李小白2 天前
Kotlin实现Retrofit风格的网络请求封装
网络·kotlin·retrofit
ZhuYuxi3332 天前
【Kotlin】const 修饰的编译期常量
android·开发语言·kotlin
jzlhll1232 天前
kotlin StateFlow的两个问题和使用场景探讨
kotlin·stateflow
Bryce李小白2 天前
Kotlin 实现 MVVM 架构设计总结
android·开发语言·kotlin
Kiri霧2 天前
Kotlin位运算
android·开发语言·kotlin
xjdkxnhcoskxbco2 天前
kotlin基础【3】
android·开发语言·kotlin