So I have a api in Scala that uses twitter.util.Future
.
In my case, I want to create 2 futures, one of which is dependent on the result of the other and return the first future:
def apiFunc(): Future[Response]={
val future1 = getFuture1()
val future2 = future1 map {
resp => processFuture1Resp(resp)
}
future1
}
So in this case, future2
is never consumed and the api returns the result of future1
before future2
is completed.
My question is - will future2
run even though the api has returned?
Further, future1
should not be affected by future2
. That is, the processing time for future2
should not be seen by any client that calls apiFunc()
. You can think of processFuture1Resp
as sending the results of getFuture1()
to another service but the client calling apiFunc()
doesn't care about that portion and only wants future1
as quickly as possible
My understanding is that futures spawn threads, but I am unsure if that thread will be terminated after the return of the main thread.
I guess a different way to ask this is - Will a twitter.util.future
always be executed? Is there a way to fire and forget a twitter.util.future
?
If you want to chain two futures where one of them processes the result of the other (and return a future), you can use a for comprehension:
This will print:
The value
finalResultOfFutures
will contain the result of chaining both futures, and you'll be sure that the first future is executed before the second one. If you don't wait for the execution offinalResultOfFutures
on the main thread (commenting the last sleep function of the main thread), you will only see:The main thread will finish before the second future has time to print anything.
Another (better) way to wait for the execution of the future would be something like this:
Await.result
will block the main thread and waits a defined duration for the result of the given Future. If it is not ready or completes with a failure, Await.result will throw an exception.EDITED
Another option is to use Monix Tasks This library allows you wrap actions (such as Futures) and have a greater control on how and when the Futures are executed. Since a Future may start its execution right after its declaration, these functionalities can be quite handy. Example:
This will print: