Reputation: 5974
Suppose I have a function like this (I use akka 2.0.2):
def foo(message: String): Future[SomeClass] =
for {
result <- actor ? message
} yield SomeClass(result)
The caller of a function sets onSuccess
and onFailure
hooks on the future, so if I want an actor to break the promise, I make it send akka.actor.Status.Failure
back to the sender. That works just fine. Now, what if I want to check some condition in foo
and return the failed future in case condition fails/succeeds?
def foo(message: String): Future[SomeClass] =
if(...) {
...//return failed future
} else {
for {
result <- actor ? message
} yield SomeClass(result)
}
What the 'return failed future' block should be like? And do I need an execution context to implement it?
Upvotes: 2
Views: 1132
Reputation: 32335
Just return an expression: Promise.failed(new Exception)
, where the exception is the one you want to fail the future with. You don't need an execution context if you are using the Scala futures and promises in the Scala standard library from 2.10.
Akka futures and promises require an implicit execution context for the failed
promise method. There should be a default execution context available in the execution context companion object, which you can use given that you have an ActorSystem
instance available.
Upvotes: 5