Reputation: 3370
I have a Play 2.1 controller in Java, and I need to call an external webservice to get some data. Then with this data result, I must call another web service with n calls, corresponding to the n results from the first webservice call.
For performance issues, I want to make the n calls in separated threads using promises.
So I would have a loop like this:
List<String> firstResults = WS.url("http://...") ///...blablabla
for(String keyword : firstResults){
Promise<ResultType> promise = play.libs.Akka.future(
new Callable<ResultType>() {
public Integer call() {
return //...
}
}
);}
How can I synchronize the n promises and then reduce the results in one response (a list of all results) using the Async API, and then return the http responses only when all calls are finished?
Not being able to know the number of calls make the problem more difficult ... (I can't declare promises as promise1, promise2 etc.)
Upvotes: 2
Views: 2035
Reputation: 12850
Promise.waitAll is what you want:
List<String> firstResults = WS.url("http://...") ///...blablabla
List<Promise<? extends ResultType>> webServiceCalls = new ArrayList<>;
for(String keyword : firstResults){
Promise<ResultType> promise = WS.url("http://...?keyboard=" + keyword).get().map(
// function of Response to ResultType
);
webServiceCalls.add(promise);
}
// Don't be confused by the name here, it's not actually waiting
Promise<List<ResultType>> results = Promise.waitAll(webServiceCalls);
return async(results.map(new Function<List<ResultType, Result>>() {
public Result apply(List<ResultType> results) {
// Convert results to ResultType
}
});
Upvotes: 4