Skip to content

Instantly share code, notes, and snippets.

@stuhood
Created July 16, 2015 20:47
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 stuhood/f382fb657146591a7946 to your computer and use it in GitHub Desktop.
Save stuhood/f382fb657146591a7946 to your computer and use it in GitHub Desktop.
implicit val timer = new MockTimer
val af = Future.sleep(10.seconds).before { Future.value("A") }
val bf = Future.sleep(10.seconds).before { Future.value("B") }
object DeadlineReached extends Exception
def selectWithin(deadline: Time)(remaining: Seq[Future[String]], valuesSoFar: Seq[String] = Seq()): Future[Seq[String]] =
if (remaining.isEmpty) {
Future.value(valuesSoFar)
} else Future.select(remaining).flatMap { s =>
val (t, nextRemaining) = s
val nextValues =
t match {
case Throw(x) =>
println(s"Whelp... should probably do something better for: $x")
valuesSoFar
case Return(v) =>
valuesSoFar :+ v
}
selectWithin(deadline)(nextRemaining, nextValues)
.raiseWithin(Time.now - deadline, DeadlineReached)
.handle {
// out of time: return what we have so far
case DeadlineReached => valuesSoFar
}
}
selectWithin(Time.now + 10.seconds)(Seq(af, bf))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment