Tuesday, August 11, 2009

Flex: Using Responder with WebService

As a newbie to Flex, I faced a scenario where I had to consume a web service within the Flex 3 ActionScript class using the class mx.rpc.soap.mxml.WebService.

On utilizing Google, I came across of blog’s which published the code that I required.
On implementing the code, strangely in my case the Result Handler and Fault Handler event handlers never got triggered, even after the web service operation had completed

So I made use of the mx.rpc.Responder class which I attached to mx.rpc.AsyncToken object returned by the operation.send( ) method. The Result and Fault handlers are attached to the Responder class.

Now the event handler’s are getting triggered as soon as the Asynchronous call to the web service ends and I am able to retrieve the data.

Code Snippet:

package testservice
{
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.rpc.AsyncToken;
import mx.rpc.Responder;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.soap.mxml.Operation;
import mx.rpc.soap.mxml.WebService;

public class CallService
{

private var serverData:ArrayCollection;

public function CallService ()
{
super();

var webService:WebService = new WebService();
webService.wsdl = "http://xyz.com/?wsdl";
webService.useProxy = false;
webService.loadWSDL();

var operation:Operation = new Operation(null,"OperationName");
operation.resultFormat = "object";

webService.operations = [operation];

var asyn:AsyncToken = webService.getOperation("OperationName ").send();
var responder:Responder = new Responder( resultHandler, faultHandler );
asyn.addResponder(responder);

}

private function faultHandler(event:FaultEvent):void{
Alert.show(event.fault.faultString);
}

private function resultHandler(event:ResultEvent):void{
serverData = new ArrayCollection(event.result.source);
}
}
}