-
-
Save tikurahul/a4e470a6a168807d471a to your computer and use it in GitHub Desktop.
Play Iteratees -- Core Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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