Created
July 11, 2013 00:20
-
-
Save ryanlecompte/5971428 to your computer and use it in GitHub Desktop.
non-blocking filter of futures
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
scala> val nums = 0 to 10 | |
res17: scala.collection.immutable.Range.Inclusive = Range(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) | |
scala> def lookup(id: Int): Future[Option[Int]] = future { if (Random.nextBoolean) Some(5) else None } | |
lookup: (id: Int)scala.concurrent.Future[Option[Int]] | |
scala> val collapsed = Future.sequence(nums.map { n => lookup(n).map { (n, _) } }) | |
reduced: scala.concurrent.Future[scala.collection.immutable.IndexedSeq[(Int, Option[Int])]] = scala.concurrent.impl.Promise$DefaultPromise@5f0900d2 | |
scala> val filtered = collapsed.map { results => results.collect { case (i, opt) if opt.isDefined => i } } | |
filtered: scala.concurrent.Future[scala.collection.immutable.IndexedSeq[Int]] = scala.concurrent.impl.Promise$DefaultPromise@7f5451cc | |
scala> Await.result(filtered, Duration.Inf) | |
res23: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 3, 4, 8) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment