Sink.foldWhile
Fold over emitted elements with a function, where each invocation will get the new element and the result from the previous fold invocation.
Signature
Description
A Sink that will invoke the given function for every received element, giving it its previous output (or the given zero value) and the element as input.
Materializes into a Future
CompletionStage
that will complete with the last state when the stream has completed, predicate p returns false, or completed with Failure if there is a failure signaled in the stream.
This operator allows combining values into a result without a global mutable state by instead passing the state along between invocations.
Example
foldWhile
is typically used to ‘fold up’ the incoming values into an aggregate with a predicate. For example, you can use foldWhile
to calculate the sum while some predicate is true.
- Scala
-
source
val r = Source(1 to 10) .runWith(Sink.foldWhile(0L)(_ < 10)(_ + _)) println(Await.result(r, 3.seconds)) // Expect prints: // 10
- Java
-
source
final int result = Source.range(1, 10) .runWith(Sink.foldWhile(0, acc -> acc < 10, Integer::sum), system) .toCompletableFuture() .get(); System.out.println(result); // Expect prints: // 10
Reactive Streams semantics
cancels never
backpressures when the previous fold function invocation has not yet completed