Skip to content

Instantly share code, notes, and snippets.

@MartinHH
Last active April 8, 2016 05:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MartinHH/a05a87269b1697d5f57a1c77db269767 to your computer and use it in GitHub Desktop.
Save MartinHH/a05a87269b1697d5f57a1c77db269767 to your computer and use it in GitHub Desktop.
package example
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.scaladsl._
object WeightExample {
def main(args: Array[String]) {
implicit val system = ActorSystem("mySystem")
import system.dispatcher
implicit val materializer = ActorMaterializer()
type Element = String
val weightFunction: Element => Int = _.length
val Limit: Int = 5
val testInput = List("One", "Two", "One", "Two", "One", "Two", "Three", ",",
"this", "is", "a", "test", "!", "!")
Source.fromIterator(() => testInput.toIterator)
.scan[(Option[Element], Int)](None, 0) { case ((_, totalWeight), elem) =>
val newWeight =
if (totalWeight > Limit) weightFunction(elem)
else totalWeight + weightFunction(elem)
(Some(elem), newWeight)
}.collect { case (Some(elem), weight) => (elem, weight > Limit) }
.splitAfter(_._2)
.fold(List.empty[Element]){ case (list, (elem, _)) => elem :: list}
.map(_.reverse)
.concatSubstreams
.runForeach(println).onComplete(_ => system.terminate())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment