Reputation: 22709
I am creating a REST API which makes a API Call in a loop. Something like this:
@RequestMapping(value = "/sendmessages", method = RequestMethod.POST)
public ResponseEntity<String> sendMessage(ModelMap model,
HttpServletRequest req, HttpServletResponse res,
@RequestBody String requestBody) throws JSONException,
Exception {
JSONObject jsonObject = new JSONObject(requestBody);
JSONArray userIdArray = jsonObject.getJSONArray(ChatConstants.USER_IDS);
for (int i = 0; i < userIdArray.length(); ++i) {
pubnub.publish(SERVER, messageObject, new Callback() {
@Override
public void successCallback(String arg0, Object arg1) {
System.out.println(arg0);
System.out.println(arg1);
}
@Override
public void errorCallback(String arg0, PubnubError arg1) {
super.errorCallback(arg0, arg1);
System.out.println(arg0);
System.out.println(arg1);
}
});
}
return new ResponseEntity<String>(HttpStatus.OK);
}
I am making a PubNub call which is an Async call and result is returned in a callback. I want to return the output of these Async calls in my API call. Any ideas, how can I track the result of these calls ?
Upvotes: 0
Views: 650
Reputation: 57421
I would introduce a 2 methods based solution. You already have the sendMessage() and you need one more checkMessageResult().
In the callback you can store results somewhere (e.g. in a Map stored in session) or in a "global" map.
Each call of send message returns some sentRequestId. Then client checks from time to time status of the request passing the sentRequestId. When callback is called the result is stored in the map Map. The checkMessageResult() just returns content from the map by the sentRequestId.
Upvotes: 1