Skip to content

Instantly share code, notes, and snippets.

@ryanlecompte
Created July 11, 2013 00:20
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 ryanlecompte/5971428 to your computer and use it in GitHub Desktop.
Save ryanlecompte/5971428 to your computer and use it in GitHub Desktop.
non-blocking filter of futures
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