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 { ... }    }}
相关推荐
Kotlin上海用户组12 小时前
Koin vs. Hilt——最流行的 Android DI 框架全方位对比
android·架构·kotlin
Kapaseker18 小时前
当Object遇到Json你可能会碰到的坑
kotlin
RichardLai8818 小时前
Kotlin Flow:构建响应式流的现代 Kotlin 之道
android·前端·kotlin
程序员江同学20 小时前
Kotlin/Native 编译流程浅析
android·kotlin
移动开发者1号21 小时前
Kotlin协程与响应式编程深度对比
android·kotlin
tq10861 天前
使用协程简化异步资源获取操作
kotlin·结构化并发
alexhilton1 天前
为什么你的App总是忘记所有事情
android·kotlin·android jetpack
移动开发者1号2 天前
Kotlin协程超时控制:深入理解withTimeout与withTimeoutOrNull
android·kotlin
移动开发者1号2 天前
Java Phaser:分阶段任务控制的终极武器
android·kotlin