An AsyncToken Primer

Do you know what an AsyncToken is?

Answer 1: The first thing I ask a Flex interviewee who claims to be proficient in Flex;)

Answer 2: 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.

Give it a try and let me know what you think!

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
# Posted By Oyun | 7/11/08 8:10 PM
Reiner's Gravatar Hello
I like to know how to control the secuence of execution ...
so kind of synchronous RPC operations ....
Thank
Reiner
# Posted By Reiner | 7/17/08 5:23 PM
cinsel urunler's Gravatar Thanks you !
# Posted By cinsel urunler | 10/22/08 9:56 AM
Paul's Gravatar Thank you! Very clear and concise.
# Posted By Paul | 11/11/08 11:35 AM
arkadas's Gravatar thanks very.
# Posted By arkadas | 11/21/08 9:42 AM
chat's Gravatar thanks.
# Posted By chat | 12/5/08 7:10 PM
erick's Gravatar I have to say this is pure gold!!! thx a million! :)
# Posted By erick | 3/19/09 3:35 AM
BlogCFC was created by Raymond Camden. This blog is running version 5.8.001.