Last active
January 27, 2016 13:53
-
-
Save atamborrino/a254cebb782267627fdd to your computer and use it in GitHub Desktop.
Future.firstSuccessfulOf
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
import scala.concurrent._ | |
import scala.util.{Success, Failure} | |
import scala.collection.immutable.Seq | |
// Returns first successful future result, or last failure if all futures failed | |
def firstSuccessfulOf[A](futures: Seq[Future[A]])(implicit executor: ExecutionContext): Future[A] = { | |
val total = futures.length | |
val counter = new java.util.concurrent.atomic.AtomicInteger(total) | |
val p = Promise[A]() | |
futures.foreach { fut => | |
fut.onComplete { | |
case Success(a) => p.trySuccess(a) | |
case Failure(failure) => | |
if (counter.decrementAndGet() == 0) p.failure(failure) | |
} | |
} | |
p.future | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment