-
-
Save sdether/ba2810107b191a390971 to your computer and use it in GitHub Desktop.
Play Enumerator, Iterator cheatsheet
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
// --- cheat sheet --- | |
// | |
// Enumerator &> -> filters the output of the enumerator through an Enumeratee | |
// Enumerator >>> -> alias for andThen; adds the output of the second enumerator after the first one is done | |
// Enumerator |>> -> feeds the output of the enumerator into the given iteratee for processing | |
// --- end of cheat sheet --- | |
// Example | |
// Iteratee that sums up the size of the input: | |
val inputLength = Iteratee.fold[Array[Byte], Int](0) { (length, bytes) => length + bytes.size } | |
// enumerator that generates strings | |
val stringEnumerator = Enumerator("one", "two", "three", "four") | |
// enumeratee that converts output from an enumerator of type String into Array[Byte] | |
val toByteArray = Enumeratee.map[String] { s => s.getBytes } | |
// let's hook them up | |
val countInput = stringEnumerator &> toByteArray |>> inputLenght | |
// --- | |
// enumerator that generates some random data every X seconds | |
val dataGenerator = Enumerator.fromCallback { () => | |
Promise.timeout(Some(new java.util.Random().nextInt(100)), 5000 milliseconds) | |
} | |
// enumeratee that converts ints to strings | |
val toStr = Enumeratee.map[Int] { x => x.toString } | |
// iteratee that prints input to the console | |
val toConsole = Iteratee.foreach[String](println(_)) | |
// and now we wire all together | |
dataGenerator &> toStr |>> toConsole |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment