Kotlin - 操作符整理

2024-11-18  本文已影响0人  JamesYang1624

1. filter

val numbersFlow = flowOf(1, 2, 3, 4, 5)
val evenNumbersFlow = numbersFlow.filter { it % 2 == 0 }

// 使用
evenNumbersFlow.collect { println(it) } // 输出: 2, 4

2. filterNot

val notEvenNumbersFlow = numbersFlow.filterNot { it % 2 == 0 }

// 使用
notEvenNumbersFlow.collect { println(it) } // 输出: 1, 3, 5

3. filterIsInstance

val mixedFlow = flowOf(1, "two", 3, "four")
val stringsFlow = mixedFlow.filterIsInstance<String>()

// 使用
stringsFlow.collect { println(it) } // 输出: "two", "four"

4. filterIsInstance(klass: KClass<R>)

val stringsFlowDynamic = mixedFlow.filterIsInstance(String::class)

// 使用
stringsFlowDynamic.collect { println(it) } // 输出: "two", "four"

5. filterNotNull

val nullableFlow = flowOf(1, null, 3, null, 5)
val nonNullFlow = nullableFlow.filterNotNull()

// 使用
nonNullFlow.collect { println(it) } // 输出: 1, 3, 5

6. map

val doubledFlow = numbersFlow.map { it * 2 }

// 使用
doubledFlow.collect { println(it) } // 输出: 2, 4, 6, 8, 10

7. mapNotNull

val transformedFlow = numbersFlow.mapNotNull { if (it % 2 == 0) it * 2 else null }

// 使用
transformedFlow.collect { println(it) } // 输出: 4, 8

8. withIndex

val indexedFlow = numbersFlow.withIndex()

// 使用
indexedFlow.collect { (index, value) -> println("Index: $index, Value: $value") }
// 输出: Index: 0, Value: 1; Index: 1, Value: 2; ...

9. onEach

numbersFlow.onEach { println("Processing: $it") }
    .collect() // 输出: Processing: 1; Processing: 2; ...

10. scan

val scannedFlow = numbersFlow.scan(0) { acc, value -> acc + value }

// 使用
scannedFlow.collect { println(it) } // 输出: 0, 1, 3, 6, 10, 15

11. runningFold

val runningFoldFlow = numbersFlow.runningFold(10) { acc, value -> acc + value }

// 使用
runningFoldFlow.collect { println(it) } // 输出: 10, 11, 13, 16, 20, 25

12. runningReduce

val runningReduceFlow = numbersFlow.runningReduce { acc, value -> acc + value }

// 使用
runningReduceFlow.collect { println(it) } // 输出: 1, 3, 6, 10, 15

13. chunked

val chunkedFlow = flowOf("a", "b", "c", "d", "e").chunked(2)

// 使用
chunkedFlow.collect { println(it) } // 输出: ["a", "b"], ["c", "d"], ["e"]
上一篇 下一篇

猜你喜欢

热点阅读