Friday, February 19, 2010

Asynchronous calls in flex

Let's consider a scenario where you make multiple call to httpservice and get different results. How will we handle this.

Let's first consider only one service call -
------------------------------------------
private function init():void{
    service.addEventListener(ResultEvent.RESULT, 
    handleResult);
    //based on type return list.
    service.request(type: "artist"); 
    service.send();
}

private function handleResult(event:ResultEvent){
     //get results and process or display
     var artistList:Array = event.result.artistList; 
}

Now suppose I want to send two request as follows -
----------------------------
private function init():void{
    service.addEventListener(ResultEvent.RESULT, 
    handleResult);
    service.request(type: "artist");
    service.send();
    
    //request is based on id get albums.
    service.request(artistId: "p_001");
    service.send();
}

private function handleResult(event:ResultEvent){
      //get results and process or display
}
----------------------------

Here is the problem, because there are two asynchronous call and only one handler, so can't distinguish between two results. So there should be separate handlers for both requests.
So it could be acheived like following - 

send() return AsynToken where we can attach responder (implements IResponder). So corresponding responder will handle it's results.

private function init():void{
     
     //service.addEventListener(ResultEvent.RESULT,   
    handleResult);  //NO NEED
    service.request(type: "artist");
    var token1:AsynToken = service.send();
    token1.addResponder(new Responder1() );

    //request is based on id get albums.
    service.request(artistId: "p_001");
    var token2:AsynToken = service.send();
    token2.addResponder(new Responder2() );

}

There are two separate responder classes
public class Responder1 implements IResponder
    {
        public function Responder1()
        {
        }

        public function result(data:Object):void
        {
            //process result in data object
        }
       
        public function fault(info:Object):void
        {
        }
       
    }

Similarly implement Responder2.