I am using the Future
API from Scala 2.10.X.
Here is my use case:
object Class1 {
def apply(f: (Int) => Future[String])(i: Int): Future[String] = {
val start = DateTime.now
val result = f(i)
result.onComplete{
case _ => println("Started at " + start + ", ended at " + DateTime.now)
}
result
}
}
Pretty simple I think: I'm adding an onComplete callback to my future. Now, I'm wondering if there is a way to add a callback for when the onComplete is done executing - in this example know when the logging is done.
Let's say my result
instance has 3 onComplete
registered, can I know when all of them have been executed? I don't think it's possible but who knows :)
Maybe an alternative would be to call map
instead of onComplete
to return a new instance of Future
:
def apply(f: (Int) => Future[String])(i: Int): Future[String] = {
val start = DateTime.now
f(i) map {
case r =>
println("Started at " + start + ", ended at " + DateTime.now)
r
}
}
But I am not sure it would keep the same behavior.
Edit: Just to clarify - there is only one instance of Future
, and I call onComplete
3 times on the same instance (Well, in my example only once, but let's say I'm calling it N times) and I want to know when the 3 callbacks are done executing due to the completion of the same Future
instance.
If you don't want to use other methods (like a CountDownLatch), then you want to use
andThen
to know when your operations complete (successfully or not, and whether or not the Future was successful).If the future fails, the mapped function by contrast isn't invoked:
Similarly, blowing up in a chained handler doesn't break subsequent operations:
For the unfortunate case of needing to wait for it:
With 1 Future and 3 onComplete
I think you're going to have to go the route of either composing your functions into a single
onComplete
call or else you'll have to do exactly what you said, usemap
:Follow the next section to find out when they all finish.
With 3 different Futures
It's very possible to know when all three
Future
s will complete. In fact, in ScalaFuture
composes!Now what does this mean? It means that
fourth
is aFuture
which does not care about the inputs of the three arguments but that, when they all are complete, it will complete itself. This is pre-packaged and made ready just for you.(Side note: In the example I'm also assuming you have all your implicits in scope.)