foldWhile

Start with current value zero and then apply the current and next value to the given function. When upstream completes or the predicate p returns false, the current value is emitted downstream.

Simple operators

Signature

Source.foldWhileSource.foldWhile Flow.foldWhileFlow.foldWhile

Description

Start with current value zero and then apply the current and next value to the given function. When upstream completes, the current value is emitted downstream.

Warning

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.

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
sourceimport org.apache.pekko
import pekko.actor.ActorSystem
import pekko.stream.scaladsl.Source

Source(1 to 10)
  .foldWhile(0)(_ < 10)(_ + _)
  .runForeach(println)
// Expect prints:
// 10
Java
sourceSource.range(1, 10)
    .foldWhile(0, acc -> acc < 10, Integer::sum)
    .runForeach(System.out::println, system);
// Expect prints:
// 100

Reactive Streams semantics

emits when upstream completes

backpressures when downstream backpressures

completes when upstream completes