scan
Emit its current value, which starts at zero
, and then apply the current and next value to the given function, emitting the next current value.
Signature
Source.scan
Source.scan
Flow.scan
Flow.scan
Description
Emit its current value, which starts at zero
, and then apply the current and next value to the given function, emitting the next current value. This means that scan
emits one element downstream before, and upstream elements will not be requested until, the second element is required from downstream.
Note that the zero
value must be immutable, because otherwise the same mutable instance would be shared across different threads when running the stream more than once.
Examples
Below example demonstrates how scan
is similar to fold
, but it keeps value from every iteration.
- Scala
-
source
val source = Source(1 to 5) source.scan(0)((acc, x) => acc + x).runForeach(println) // 0 (= 0) // 1 (= 0 + 1) // 3 (= 0 + 1 + 2) // 6 (= 0 + 1 + 2 + 3) // 10 (= 0 + 1 + 2 + 3 + 4) // 15 (= 0 + 1 + 2 + 3 + 4 + 5)
- Java
-
source
Source<Integer, NotUsed> source = Source.range(1, 5); source.scan(0, (acc, x) -> acc + x).runForeach(System.out::println, system); // 0 (= 0) // 1 (= 0 + 1) // 3 (= 0 + 1 + 2) // 6 (= 0 + 1 + 2 + 3) // 10 (= 0 + 1 + 2 + 3 + 4) // 15 (= 0 + 1 + 2 + 3 + 4 + 5)
Reactive Streams semantics
emits when the function scanning the element returns a new element
backpressures when downstream backpressures
completes when upstream completes