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 { ... }    }}
相关推荐
Rysxt_6 小时前
Kotlin前景深度分析:市场占有、技术优势与未来展望
android·开发语言·kotlin
莫白媛6 小时前
Android开发之Kotlin 在 Android 开发中的全面指南
android·开发语言·kotlin
天勤量化大唯粉1 天前
基于距离的配对交易策略:捕捉价差异常偏离的均值回归机会(天勤量化代码实现)
android·开发语言·python·算法·kotlin·开源软件·策略模式
hudawei9961 天前
kotlin冷流热流的区别
android·开发语言·kotlin·flow··冷流·热流
hudawei9961 天前
对比kotlin和flutter中的异步编程
开发语言·flutter·kotlin·异步·
モンキー・D・小菜鸡儿1 天前
Android11 新特性与适配指南
android·kotlin·安卓新特性
starrycode8882 天前
【每日一个知识点】Kotlin基础语法核心学习笔记
笔记·学习·kotlin
alexhilton3 天前
学会在Jetpack Compose中加载Lottie动画资源
android·kotlin·android jetpack
用户69371750013843 天前
29.Kotlin 类型系统:智能转换:类型检查 (is) 与类型转换 (as)
android·后端·kotlin
用户69371750013843 天前
30. Kotlin 扩展:为“老类”添“新衣”:扩展函数与扩展属性
android·后端·kotlin