Fold over emitted element with a function, where each invocation will get the new element and the result from the previous fold invocation.
Fold over emitted element 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
Materializes into a
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.
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.
val source = Source(1 to 100) val result: Future[Int] = source.runWith(Sink.fold(0)((acc, element) => acc + element)) result.map(println) // 5050
Source<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
backpressures when the previous fold function invocation has not yet completed