There are several solutions depending on the architecture of your project. The main idea is to fire the event (or call callback) when service receive response and handle it in the caller. The simplest way in your example is to return the weatherService
object in the callService
method and add the same listeners in the caller (ResultEvent.RESULT
and FaultEvent.FAULT
). The minus of this solution is that you have to parse the raw server response in caller rather than to work with some parsed value objects but as I noticed all depends on your project data flow.
UPD: the example of callback usage:
//map for storing the {service:callback} linkage
private var callbacks:Dictionary = new Dictionary(true);
/*
callback is a function like: function(success:Boolean, data:Object):void
*/
private function callService(callback:Function):void
{
var requestObj:Object = {};
requestObj.q = cityName.text.toString();
requestObj.format = FORMAT;
requestObj.num_of_days = cNUMBER_OF_DAYS;
requestObj.key = API_KEY;
var weatherService:HTTPService = new HTTPService();
weatherService.resultFormat = "object";
weatherService.showBusyCursor = true;
weatherService.request = requestObj;
weatherService.addEventListener(ResultEvent.RESULT, weatherService_handler);
weatherService.addEventListener(FaultEvent.FAULT, weatherService_handler);
var token:AsyncToken = weatherService.send();
var obj:Object = {callback:callback, service:weatherService};
callbacks[token.message.messageId] = obj;
}
protected function weatherService_handler(event:Event):void
{
var success:Boolean = event.type == ResultEvent.RESULT;
var token:AsyncToken = success ? ResultEvent(event).token : FaultEvent(event).token;
var obj:Object = callbacks[token.message.messageId]
var service:HTTPService = obj.service;
service.removeEventListener(ResultEvent.RESULT , weatherService_handler);
service.removeEventListener(FaultEvent.FAULT, weatherService_handler);
var data:Object = success ? ResultEvent(event).result : FaultEvent(event).fault;
var callback:Function = obj.callback;
delete callbacks[event.target];
callback(success, data);
}