Last active
August 29, 2015 13:55
-
-
Save langley/8700956 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Code snippets to illustrate working with the | |
// Enumeratee api from Play Framework | |
// http://www.playframework.com/documentation/2.2.x/Iteratees | |
// You should create a play app and then launch the scala console from it. | |
// Then you can paste these snippets in to experiment with iteratees | |
// in the scala REPL. | |
import play.api.libs.iteratee._ | |
import play.api.libs.concurrent.Execution.Implicits._ | |
// And we'll need some extra imports to use Await.. which is really useful because | |
// Iteratees, Enumerators and Eneratees are all about asynchronous processing and futures | |
import scala.concurrent.Await | |
import scala.concurrent.duration._ | |
import scala.language.postfixOps | |
// Note: all of these examples except the last one don't really need the Await, but it's cleaner to use it | |
// otherwise you end up with odd interleaving of the printlns and the console's output. | |
// Create an Iteratee that will consume Strings and print them | |
val printlnIterateeForStrs = Iteratee.foreach[String](str => println(s"""printlnIterateeForStrs saw: $str""")) | |
// Create an Enumerator that will produce Strings | |
val strEnumerator: Enumerator[String] = Enumerator("1", "2", "3") | |
// Apply the Enumerator to the Iteratee | |
Await.result(strEnumerator(printlnIterateeForStrs), 2 seconds) | |
// Next line is the same as the above | |
Await.result(strEnumerator |>> printlnIterateeForStrs, 2 seconds) | |
// Now make a joined enumerator,iteratee pair that let's us create an output (enumerator) transformed by a consumer (iteratee) | |
val (iteratee, enumerator) = Concurrent.joined[String] | |
val inputTransformerIteratee = Enumeratee.map { chunk: String => "before_" ++ chunk ++ "_after" } &>> iteratee | |
strEnumerator |>> inputTransformerIteratee // |>> alias for apply this will drive input that we'll see come out the enumerator | |
enumerator |>> printlnIterateeForStrs // now see the transformed output |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment