Skip to content

Instantly share code, notes, and snippets.

@mcolmant
Last active February 17, 2018 19:37
Show Gist options
  • Save mcolmant/28f0fed14aecdc2a51c8 to your computer and use it in GitHub Desktop.
Save mcolmant/28f0fed14aecdc2a51c8 to your computer and use it in GitHub Desktop.
Example to convert a list of futures to a future of list (by processing the exception).
import akka.actor._
import scala.concurrent.duration._
import scala.concurrent._
import akka.pattern.ask
import scala.concurrent.ExecutionContext.Implicits.global
import akka.util._
import scala.util._
class TestActor extends Actor {
def receive = {
case i: Int => {
// Mix Success/failure future with conversion => sends a Future[List[T]] with the successful ones only.
sender ! Future.sequence(((for(i <- 0 to i) yield Future { i }).toList :+ context.actorSelection("1").ask(1)(Timeout(1.seconds))).map(f => f.map(Success(_)).recover({case e => Failure(e)}))).map(_.collect{ case Success(x) => x})
}
}
}
// Use case
implicit val timeout = Timeout(1.seconds)
val system = ActorSystem("system")
val actor = system.actorOf(Props(classOf[TestActor]))
val ans = Await.result(actor ? 10, 1.seconds).asInstanceOf[Future[List[Int]]]
ans onSuccess {
case l => println(l)
}
Test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment