Skip to content

Instantly share code, notes, and snippets.

@phdoerfler
Created May 4, 2021 11:57
Show Gist options
  • Save phdoerfler/557a4cc4031475def4a9143a9cebccbc to your computer and use it in GitHub Desktop.
Save phdoerfler/557a4cc4031475def4a9143a9cebccbc to your computer and use it in GitHub Desktop.
package io.doerfler
/**
* As an alternative consider flatMapConcat and mapConcat of Akka Streams.
*/
abstract class IteratorThatKeepsOnGiving[T] extends Iterator[T] {
private var currentIter: Iterator[T] = Iterator.empty[T]
private var currentElement: Option[T] = None
def nextIterator(lastElement: Option[T]): Iterator[T]
def fetchNewBatch(lastElement: Option[T]) = {
currentIter = nextIterator(lastElement)
}
def hasNext: Boolean = currentIter.hasNext || {
fetchNewBatch(currentElement)
currentIter.hasNext
}
def next(): T = {
currentIter.nextOption() match {
case v @ Some(value) =>
currentElement = v
value
case None =>
fetchNewBatch(currentElement)
next()
}
}
}
object IteratorThatKeepsOnGiving {
def apply[T](f: Option[T] => Iterator[T]) = new IteratorThatKeepsOnGiving[T] {
def nextIterator(lastElement: Option[T]): Iterator[T] = f(lastElement)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment