reduce

Start with first element and then apply the current and next value to the given function, when upstream complete the current value is emitted downstream.

Simple operators

Signature

Source.reduceSource.reduce Flow.reduceFlow.reduce

Description

Start with first element and then apply the current and next value to the given function, when upstream complete the current value is emitted downstream. Similar to fold.

Example

reduce will take a function and apply it on the incoming elements in the Stream and only emits its result when upstream completes. Here, it will add the incoming elements.

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

Reactive Streams semantics

emits when upstream completes

backpressures when downstream backpressures

completes when upstream completes

Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.