I have two ListenableFutures which are completed on other threads. Each future is of a different type, and I wish to use both of their results when they are both complete.
Is there an elegant way to handle this using Guava?
I have two ListenableFutures which are completed on other threads. Each future is of a different type, and I wish to use both of their results when they are both complete.
Is there an elegant way to handle this using Guava?
If you want some sort of type safety you can do the following:
In this case
Composite
can be aPair<A, B>
from Apache Commons if you like.Also, a failure in either future will result in a failure in the resulting combined future.
Another solution would be to take a look at Trickle from the team at Spotify. The GitHub README has an example which shows a solution to a similar problem.
There are undoubtedly other solutions but this is the one that popped into my head.
Since Guava v20.0 you can use:
Look at java docs example here
If you want some type safety, you can combine result of 2 different independent tasks by using
EventBus
from the sister Guavacom.google.common.eventbus
packageFor the example sake, let's assume that one of you
Futures
returnsInteger
and the otherDouble
.First, create an accumulator (other names builder, collector, etc) class that you will register as an event sink with EventBus. As you can see it's really a POJO which will hanlde
Integer
andDouble
eventsHere is the implementation of the method that will take 2 futures and will combine them into an accumulator.
Not really elegant, but should do the job.
Or, more elegant, but you'll need casts:
Here is a simple example that would perform the addition of 2 listenable futures: