Skip to content

Instantly share code, notes, and snippets.

@oscarrenalias
Created October 18, 2012 21:35
Show Gist options
  • Save oscarrenalias/3914875 to your computer and use it in GitHub Desktop.
Save oscarrenalias/3914875 to your computer and use it in GitHub Desktop.
Cheatsheet Play enumerators, enumeratees, iterators and iteratees
// --- 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