Sink.fold

Fold over emitted elements with a function, where each invocation will get the new element and the result from the previous fold invocation.

Sink operators

Signature

Sink.foldSink.fold

Description

Fold over emitted elements with a function, where each invocation will get the new element and the result from the previous fold invocation. The first invocation will be provided the zero value.

Materializes into a Future CompletionStage that will complete with the last state when the stream has completed.

This operator allows combining values into a result without a global mutable state by instead passing the state along between invocations.

Example

This example reads the numbers from a source and do some calculation in the flow part and in the end uses Sink.fold and adds the incoming elements.

Scala
sourceval source = Source(1 to 100)
val result: Future[Int] = source.runWith(Sink.fold(0)((acc, element) => acc + element))
result.map(println)
// 5050
Java
sourceSource<Integer, NotUsed> source = Source.range(1, 100);
CompletionStage<Integer> sum =
    source.runWith(Sink.fold(0, (res, element) -> res + element), system);
sum.thenAccept(System.out::println);

Reactive Streams semantics

cancels never

backpressures when the previous fold function invocation has not yet completed