Skip to content

Instantly share code, notes, and snippets.

@alexandrepiveteau
Created April 1, 2021 09:12
Show Gist options
  • Save alexandrepiveteau/60f5e184c8252b7edb3b3daa8dfd9dd7 to your computer and use it in GitHub Desktop.
Save alexandrepiveteau/60f5e184c8252b7edb3b3daa8dfd9dd7 to your computer and use it in GitHub Desktop.
An operator that combines scan(...) and transform { ... } for Kotlin flows
/**
* 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