Source.cycle

Stream iterator in cycled manner.

Source operators

Signature

Source.cycleSource.cycle

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.

Examples

Scala
sourceSource
  .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
sourcefinal Source<Integer, NotUsed> source = Source.cycle(() -> Arrays.asList(1, 2, 3).iterator());
CompletionStage<List<Integer>> result = source.grouped(9).runWith(Sink.head(), system);
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
sourceval empty = Iterator.empty
Source
  .cycle(() => empty)
  .runWith(Sink.head)
  // This will return a failed future with an `IllegalArgumentException`
Java
sourceIterator<Integer> emptyIterator = Collections.<Integer>emptyList().iterator();
Source.cycle(() -> emptyIterator)
    .runWith(Sink.head(), system)
    // stream will be terminated with IllegalArgumentException

Reactive Streams semantics

emits the next value returned from cycled iterator

completes never