diff options
Diffstat (limited to 'kotlinx-coroutines-core/common/src/flow/operators/Transform.kt')
-rw-r--r-- | kotlinx-coroutines-core/common/src/flow/operators/Transform.kt | 20 |
1 files changed, 17 insertions, 3 deletions
diff --git a/kotlinx-coroutines-core/common/src/flow/operators/Transform.kt b/kotlinx-coroutines-core/common/src/flow/operators/Transform.kt index d163d9c0..59298864 100644 --- a/kotlinx-coroutines-core/common/src/flow/operators/Transform.kt +++ b/kotlinx-coroutines-core/common/src/flow/operators/Transform.kt @@ -15,7 +15,7 @@ import kotlinx.coroutines.flow.internal.unsafeFlow as flow import kotlinx.coroutines.flow.unsafeTransform as transform /** - * Returns a flow containing only values of the original flow that matches the given [predicate]. + * Returns a flow containing only values of the original flow that match the given [predicate]. */ public inline fun <T> Flow<T>.filter(crossinline predicate: suspend (T) -> Boolean): Flow<T> = transform { value -> if (predicate(value)) return@transform emit(value) @@ -82,9 +82,23 @@ public fun <T> Flow<T>.onEach(action: suspend (T) -> Unit): Flow<T> = transform * flowOf(1, 2, 3).scan(emptyList<Int>()) { acc, value -> acc + value }.toList() * ``` * will produce `[], [1], [1, 2], [1, 2, 3]]`. + * + * This function is an alias to [runningFold] operator. + */ +@ExperimentalCoroutinesApi +public fun <T, R> Flow<T>.scan(initial: R, @BuilderInference operation: suspend (accumulator: R, value: T) -> R): Flow<R> = runningFold(initial, operation) + +/** + * Folds the given flow with [operation], emitting every intermediate result, including [initial] value. + * Note that initial value should be immutable (or should not be mutated) as it is shared between different collectors. + * For example: + * ``` + * flowOf(1, 2, 3).scan(emptyList<Int>()) { acc, value -> acc + value }.toList() + * ``` + * will produce `[], [1], [1, 2], [1, 2, 3]]`. */ @ExperimentalCoroutinesApi -public fun <T, R> Flow<T>.scan(initial: R, @BuilderInference operation: suspend (accumulator: R, value: T) -> R): Flow<R> = flow { +public fun <T, R> Flow<T>.runningFold(initial: R, @BuilderInference operation: suspend (accumulator: R, value: T) -> R): Flow<R> = flow { var accumulator: R = initial emit(accumulator) collect { value -> @@ -100,7 +114,7 @@ public fun <T, R> Flow<T>.scan(initial: R, @BuilderInference operation: suspend * * For example: * ``` - * flowOf(1, 2, 3, 4).runningReduce { (v1, v2) -> v1 + v2 }.toList() + * flowOf(1, 2, 3, 4).runningReduce { acc, value -> acc + value }.toList() * ``` * will produce `[1, 3, 6, 10]` */ |