During my last mini flash project I created a project designed to help me with async calls in AS3. I hope that it helps you too. You can find the project on "my github account":http://github.com/vosechu/required_sequence.
h2. Intro
Required Sequence is a tiny AS3 library that mandates that certain bits of code run before other bits of code. I've heard that Senocular has an "excellent version of this":http://www.senocular.com/flash/actionscript/?file=ActionScript_3.0/com/senocular/events/Sequence.as but I could never quite grok his library. There's also the apparently magical BulkLoader "which you can find here":http://code.google.com/p/bulk-loader/. Before I found those two libraries I had already written my own and it works quite well for me.
h2. Background
Required Sequence is essentially an implementation of the Publish/Subscribe design pattern in AS3. It relies on the principle that when an important configuration process finishes it will dispatch an Event on the main class. Other processes that are interested in this merely tell their Required Sequence instance to listen for that Event and execute some code when it happens.
For example, if you need to load an XML config file before doing anything else you could easily write something like this:
1
2
3
4
5
rs.requireFlag(MyClass.CONFIG_LOADED,
function () {
// Do the rest of my program
}
);
package
{
import com.chuckvose.utils.RequiredSequence;
public class MyClass
{
public static const CONFIG_LOADED = 'configLoaded';
public var rs:RequiredSequence;
public function MyClass()
{
rs = new RequiredSequence();
// Ensure that we see the CONFIG_LOADED Event before doing anything else
rs.requireFlag(MyClass.CONFIG_LOADED,
function () {
// Do the rest of my program
}
);
}
public function loadConfig()
{
// Do some stuff
dispatchEvent(new Event(MyClass.CONFIG_LOADED));
}
}
}
rs.requireFlagWithRetry(MyClass.CONFIG_LOADED,
// Code that would be necessary to generate the interesting Event. You do
// not need to invoke this manually, it will run this code immediately.
function () {
loadConfig();
},
// Code to run after we see the interesting Event.
function () {
// Do the rest of my program
}
);
var retries = 5; // Max number of tries
var period = 2000; // Milliseconds between tries
rs.requireFlagWithRetry(MyClass.CONFIG_LOADED,
// Code that would be necessary to generate the interesting Event. You do
// not need to invoke this manually, it will run this code immediately.
function () {
loadConfig();
},
// Code to run after we see the interesting Event.
function () {
// Do the rest of my program
},
retries,
period
);
rs.requireFlagRepeatedly(MyClass.PANE_LOADED, function () {
refreshCanvas();
hideSpinner();
});
rs.requireFlags([MyClass.CONFIG_LOADED, MyClass.LOCATION_LOADED],
function () {
drawWeatherDisplay();
}
);