cycle

Stream iterator in cycled manner.

Source operators

Signature

def cycle[T](f: () ⇒ Iterator[T]): Source[T, NotUsed]

Description

Stream iterator in cycled manner. Internally a new iterator is being created to cycle the one provided via argument meaning when the original iterator runs out of elements to process it will start all over again from the beginning of the iterator provided by the evaluation of provided parameter. If the method argument provides an empty iterator the stream will be terminated with an exception.

emits the next value returned from cycled iterator

completes never

Examples

Scala
Source.cycle(() ⇒ List(1, 2, 3).iterator)
  .grouped(9)
  .runWith(Sink.head)
  // This will produce the Seq(1, 2, 3, 1, 2, 3, 1, 2, 3)
Java
final Source<Integer, NotUsed> source = Source.cycle(() -> Arrays.asList(1, 2, 3).iterator());
CompletionStage<List<Integer>> result = source.grouped(9).runWith(Sink.head(), materializer);
List<Integer> emittedValues = result.toCompletableFuture().get();
assertThat(emittedValues, is(Arrays.asList(1, 2, 3, 1, 2, 3, 1, 2, 3)));

When iterator is empty the stream will be terminated with IllegalArgumentException

Scala
val empty = Iterator.empty
Source.cycle(() ⇒ empty)
  .runWith(Sink.head)
  // This will return a failed future with an `IllegalArgumentException`
Java
Iterator<Integer> emptyIterator = Collections.<Integer>emptyList().iterator();
Source.cycle(() -> emptyIterator)
    .runWith(Sink.head(), materializer)
    // stream will be terminated with IllegalArgumentException
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.