Skip to content

Instantly share code, notes, and snippets.

@tikurahul tikurahul/iteratees.scala Secret
Created Jun 6, 2014

Embed
What would you like to do?
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
You can’t perform that action at this time.