Skip to content

Instantly share code, notes, and snippets.

object FutureOps extends FutureOps
trait FutureOps {
def toTry[A](self: Future[A])(implicit ec: ExecutionContext): Future[Try[A]] = {
val p = Promise[Try[A]]()
self onComplete { case result => p.success(result) }
p.future
}
def takeFirstMatch[A](futures: Traversable[Future[A]], predicate: A => Boolean)(implicit ec:ExecutionContext): Future[Option[A]] = {
if(futures.nonEmpty) {
val promise = Promise[Option[A]]()
object FutureOps extends FutureOps
trait FutureOps {
def takeFirstMatch[A](futures: Traversable[Future[A]], predicate: A => Boolean)(implicit ec:ExecutionContext): Future[Option[A]] = {
if(futures.nonEmpty) {
val promise = Promise[Option[A]]()
val completedCount = new java.util.concurrent.atomic.AtomicInteger(0)
val allDoneLatch = Promise[Unit]
def maybeAllDone() {
// Note: check and execute normally creates a race but only one of the futures can cause the final count to be reached
if(completedCount.incrementAndGet() == futures.size) {