Skip to content

Instantly share code, notes, and snippets.

@tikurahul
Created June 6, 2014 00:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tikurahul/a4e470a6a168807d471a to your computer and use it in GitHub Desktop.
Save tikurahul/a4e470a6a168807d471a to your computer and use it in GitHub Desktop.
Play Iteratees -- Core Example
import play.api.libs.iteratee._
import scala.collection.mutable.ListBuffer
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent._
import scala.concurrent.duration._
object Main extends App {
val enumerator = new Enumerator[String] {
val items = 1 to 10 map (i => i.toString)
var index = 0
override def apply[A](i: Iteratee[String, A]): Future[Iteratee[String, A]] = {
println("Inside apply")
i.fold({
step => {
step match {
case Step.Done(result, remaining) => {
println("Step.Done")
Future(i)
}
case Step.Cont(k: (Input[String] => Iteratee[String, A])) => {
println("Step.Cont")
if (index < items.size) {
val item = items(index)
println(s"El($item)")
index += 1
val newIteratee = k(Input.El(item))
// recursive apply
apply(newIteratee)
} else {
println("EOF")
Future(k(Input.EOF))
}
}
case Step.Error(message, input: Input[String]) => {
println("Step.Error")
Future(i)
}
}
}
})
}
}
val iteratee = new Iteratee[String, Unit] {
override def fold[B](folder: (Step[String, Unit]) => Future[B])(implicit ec: ExecutionContext): Future[B] = {
val buffer: ListBuffer[String] = ListBuffer()
def stepFn(in: Input[String]): Iteratee[String, Unit] = {
in match {
case Input.Empty => this
case Input.EOF => Done({
println(s"Completed consuming the iteratee with result ${buffer.mkString("--")}")
}, Input.Empty)
case Input.El(el) => {
buffer += el
Cont(stepFn)
}
}
}
folder(Step.Cont(stepFn))
}
}
Await.result(enumerator |>>> iteratee, Duration.Inf)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment