An AsyncToken Primer

The official docs describe it like this: “This class provides a place to set additional or token-level data for asynchronous RPC operations. It also allows an IResponder to be attached for an individual call. The AsyncToken can be referenced in ResultEvent and FaultEvent from the token property.”

A bit confusing if you’re not familiar with the asynchronous nature of remote calls in Flex. I’ve run into a lot of folks who don’t know about this handy class so I’ll try to shed some light.

Whenever you make one or more external calls from your Flex/AIR application, you never know if or when those calls will return results (or faults) nor the order in which they will return. Even though you call remote objects “RO1”, “RO2” and “RO3” in order, they may return in a different order. You might want different handlers for these results as well.

One way to keep track of the calls is to assign an AsyncToken to each call.

Instead of making your remote calls like this:

myRO.myRemoteMethdod( )

You would do this:

var token:AsyncToken = myRO.myRemoteMethdod( )

(Make sure you import mx.rpc.AsyncToken)

You now have a variable, “token”, which represents this particular call. Now you can assign token its own result and fault handlers like this:

token.addResponder( myResponderClass );

…where the myResponderClass class implements IResponder. Implementing IResponder simply means defining two methods with the following signatures:

public function result(data:Object):void
public function fault(info:Object):void

So you can set the result and fault handlers for your remote calls at call time rather than hard coding them into your RemoteObject, HTTPService or WebService tags. This is exactly the way Cairngorm and other microarchitectures operate.

A final cool feature of AsyncToken is that it’s a dynamic class, which means that you can add properties to the token when you make the remote call, then read those properties back in the result/fault handlers.

~ by mjcprasad2000 on July 11, 2009.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: