Source.iterate

Creates a sequential Source by iterating with the given predicate, function and seed.

Source operators

Signature

Source.iterateSource.iterate

Description

Creates a sequential Source by iterating with the given hasNext predicate and next function, starting with the given seed value. If the hasNext function returns false for the seed, the Source completes with empty.

Warning

The same seed value will be used for every materialization of the Source so it is mandatory that the state is immutable. For example a java.util.Iterator, Array or Java standard library collection would not be safe as the fold operation could mutate the value. If you must use a mutable value, combining with Source.lazySource to make sure a new mutable zero value is created for each materialization is one solution.

Examples

The next example shows how to craet

Scala
sourcedef countTo(n: Long): Source[Long, NotUsed] = Source
  .iterate(1L)(_ => true, _ + 1)
  .take(n)
Java
sourcestatic Source<Long, NotUsed> countTo(long n) {
  return Source.iterate(1L, i -> true, i -> i + 1).take(n);
}

Reactive Streams semantics

emits when there is demand and the next function returns.

completes when the haxNext predicate returns false.