Reputation: 3475
i have two actors they can either return the Result which is a boolean value in my case or they can throw an exception here is my code
val futureA: Future[Boolean] = ask(ActorA, MessageA(obj)).mapTo[Boolean]
val resultA = Await.result(futureA, timeout.duration) //can return boolean or throw an exception
val futureB: Future[Boolean] = ask(ActorB, MessageB(obj)).mapTo[Boolean]
val resultb = Await.result(futureB, timeout.duration)//can return boolean or throw an exception
Here i want to achieve
scenario-1 if futureA and FutureB Succeed i should get something like (futureResponseA,futureResponseB) //(true, true)
scenario-2 if futureA fails it should proceed with FutureB if it return successfully i should get something like (exceptionOfFutureA,resultofFutureB)
scenario-3 if futureA return successfully and futureB fails i should get something like (futureResponseA,exceptionOfFutureB)
scenario-4 if futureA and futureB both failed i should get something like (exceptionOfFutureA,exceptionOfFutureB)
for that i tried with val futureA = ask(ActorA, MessageA(obj)).mapTo[Boolean] val futureB = ask(ActorB, MessageB(obj)).mapTo[Boolean]
val f = Try {Future.sequence(List(futureA, futureB))}
val result = Await.result(f, Duration.Inf)
but i am getting error on this val result
line
found : scala.util.Try[scala.concurrent.Future[List[Boolean]]]
[error] required: scala.concurrent.Awaitable[?]
How can i archive these scanerios please guide
Upvotes: 0
Views: 225
Reputation: 51271
A Try
isn't an Awaitable
, and a Future
won't throw an exception, but the Await
can. So you need to wrap the Await
with a Try
and, since you want to capture either or both failures, that means 2 different Await
s.
val resultTuple = (Try(Await.result(futureA, Duration.Inf))
,Try(Await.result(futureB, Duration.Inf)))
The result type is Tuple2[Try[Boolean],Try[Boolean]]
, which covers the 4 scenarios you laid out: (Success,Success) (Success,Failure) (Failure,Success) (Failure,Failure)
Upvotes: 3