Created
April 1, 2021 09:12
-
-
Save alexandrepiveteau/60f5e184c8252b7edb3b3daa8dfd9dd7 to your computer and use it in GitHub Desktop.
An operator that combines scan(...) and transform { ... } for Kotlin flows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Applies [transform] function to each value of the given flow. | |
* | |
* The receiver transforms is [FlowCollector] and thus [transform] is a flexible block which can | |
* transform the given element, skit it or emit multiple elements. | |
* | |
* Additionally, this transform is stateful : each time an item is processed, it is transformed and | |
* passed around for the next invocations of [transform]. | |
* | |
* @param T the type of the elements of the given flow. | |
* @param R the type of the elements of the produced flow. | |
* @param S the type of the passed state. | |
*/ | |
inline fun <T, R, S> Flow<T>.scanTransform( | |
initial: S, | |
@BuilderInference crossinline transform: suspend FlowCollector<R>.(value: T, state: S) -> S, | |
): Flow<R> = flow { | |
var state = initial | |
collect { elem -> state = transform(this, elem, state) } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment