Reputation: 23154
Here is an example from scaladoc for andThen:
val f = Future { 5 }
f andThen {
case r => sys.error("runtime exception")
} andThen {
case Failure(t) => println(t)
case Success(v) => println(v)
}
Doesn't the line case r => sys.error("runtime exception")
throw an exception no matter what the Future ends up to be? Really doesn't make any sense to me, but maybe I've missed something.
Upvotes: 2
Views: 485
Reputation: 14825
Yes, it throws an exception no matter what the Future ends up to be.
Throwing the exception could serve as a message for the thread it which the exception is thrown.
Generally,
andThen is used for executing some side effecting code after the given future is completed and the result type of the operation after andThen is the same original future's result. So, you can pattern match and expect the same result that of the original future.
In your case side effecting operation is throwing an exception, but it can be any other useful side effecting operation like writing to file, closing the resources etc
Here is the implementation of andThen
from standard Scala library.
andThen
is used to run some side effecting operation once the future on which it is invoked it completed, but the thing to notice is the result type of the whole operation will be the future with original future result.
def andThen[U](pf: PartialFunction[Try[T], U])(implicit executor: ExecutionContext): Future[T] = {
val p = Promise[T]()
onComplete {
case r => try pf.applyOrElse[Try[T], Any](r, Predef.conforms[Try[T]]) finally p complete r
}
p.future
}
Notice after the andThen
operation future with the result of the original future is returned.
As said by @Yuval Itzchakov, You could use it for throwing the exceptions on to the main thread. But Generally it is used for side effecting after the completion of a future.
Upvotes: 3
Reputation: 149626
Doesn't the line
case r => sys.error("runtime exception")
throw an exception no matter what the Future ends up to be?
Yes, it does. But one thing you need to remember that exceptions that are thrown inside a Future
aren't automatically re-thrown on the main execution thread, they need to be handled and rethrown from the main thread for the program to terminate.
All andThen
allows you to do is execute some side-effecting method, in order, and continue on the composition of the futures. There are arbitrary many things that may need side effecting attention, such as handling open resources. If all you want is to compose the futures, I'd go with Future.map
instead.
Upvotes: 1