Add

QueueLoader AS3 rev 7 + Garbage Collection + SoundManager


Latest Version Info:
Click here for the current rev

Click here for the usage guide

Click here for the change log

Also click here for any posts related to the latest changes:
QueueLoader Updates

First things first. I've thrown in an additional utility that may or may not turn into it's own project. Most likely it will as I hope to add gapless playback of loops, sound mixing, etc. But I'm already getting ahead of myself:) The reason I included my SoundManager utility is to illustrate how easy it is to use the new feature of accessing loaded swf library assets, as well as using it in a more advance management type setting. There's a lot to cover, but first let me go over the updates I made to this revision.

  • Added a stop() method for stopping the queue. resume() is in the works.
  • Added LoaderContext for accessing the classes and references in QueueLoaded external swf.
  • Added an error dispatch for an undefined target/container.
  • Added a dispose() method for unloading loaded items from memory for Garbage Collection. More on this later.
  • More cleanup and optimization of code

The most significant changes I will go over is with the LoaderContext and dispose() method. The rest are pretty self explanatory.

dispose() + Garbage Collection
This download is a lot heavier in file size as I've included some large images to clearly indicate what's happening with the Garbage Collector. I'm not going to go into too much detail on how Garbage Collection works. Essentially it is the process the Actionscript Virtual Machine uses to free up/dump unused memory. It does this intermittently and during times of low processing load, or when the memory has reached a certain level and needs to flush. To deal with this it is important to null out your variables and use removeChild to remove instances from a Display object. AS3 will retain the object in memory if there is a reference to it anywhere in the code. This can be a pain when trying to track data flow so it's better to keep this in mind when planning your plan of attack. To learn more about Garbage Collection, check out Grant Skinner's posts here.

I've included monitoring of garbage collection in the source example. System.totalMemory is the property for getting this info. But wait! There are some important things to be aware of.

  • Either there is a bug with System.totalMemory, or with the Loader.unload() method, so you will need to see changes to the GC in the browser.
  • Because of the above issue I have set the publish for local access only, so just make a note
  • System.totalMemory will give you what it says, total memory. So if you have other flash apps open in the browser you will see the memory used for those apps added to your QueueLoader Example. So be sure to close everything out.

When you dispose of a section that has used QueueLoader for loading of assets, you would use dispose() to remove the loaded assets and ready them for Garbage Collection. Lets assume we've set up a QueueLoader and it's already loaded it's assets, say for an image gallery. Here's the block of code we would use to set up the QueueLoaded assets and the loader for GC:

_oLoader.dispose();
 
// Delete the QueueLoader containers
while(imageContainer.numChildren > 0){
	imageContainer.removeChildAt(0);
}
 
_oLoader = null;

You can clearly see this working in the example fla, but you get the idea. On to the next exciting feature…

Accessing externally loaded classes and library assets:
First caveat to this. Sandbox security issues come into play if you are loading things across domains. For this example we are assuming you are loading within the same domain. QueueLoader will do this, but you need to add some extra code. For more on cross scripting go here.

This feature allows you to add Library assets to an external swf, export them for actionscript as classes, and access those classes in your parent swf. This is great for loaded sounds, images, interface widgets, etc. Personally I use a separate swf for each library asset type. This also helps if you want to add a Manager class to one of your external swf files. In this example I added the SoundManager class.

You would do this by adding:

//Definition vars for accessing loaded swf libary classes in this scope
var addedDefinitions:LoaderContext = new LoaderContext();
addedDefinitions.applicationDomain = ApplicationDomain.currentDomain;
 
 
// Scope and Instantiate variables
var _oLoader:QueueLoader = new QueueLoader(false, addedDefinitions);

and then once your assets are loaded using QueueLoader you would access them using:

var Loop1Reference:Class = getDefinitionByName("Loop1") as Class;
var loop1:Sound = new Loop1Reference();
soundChannel = loop1.play();

I know I'm using code snippets so if it seems unclear, open up the queueloader.fla and you can see all of this in its entirety.

SoundManager
SoundManager is a class I added that may or may not be used in conjunction with QueueLoader. It's in its infancy so this class is pretty straight forward. Basically what is happening is on the first frame of the externalsounds.swf there is code to add the library assets intro the SoundManager.

import com.hydrotik.utils.SoundManager;
 
SoundManager.getInstance().addItem(new Glitch1());
SoundManager.getInstance().addItem(new Glitch2());
SoundManager.getInstance().addItem(new Loop1());

Now anywhere in your application you can now play these sounds. Check out the source for more info.

My thanks to those who have commented and brought issues to my attention. Helps me to enhance this class and make it more powerful for simple as well as advanced usage. I always welcome your constructive criticism and suggestions for upcoming revisions. Please keep this in mind though. QueueLoader is a utility, and most of the control and administrative functions should be handled outside of the utility in its parent class.

If you're using QueueLoader on a project or have used it, I'd love to hear about it!

Enjoy! :)
Donovan


A more recent version of this code has been posted! Go HERE

The Discussion

see what everyone is saying

  • mosesoak October 30th, 2007 at 2:19 am #1

    Hey D this is sweet stuff… you're really ripping up the AS3, nice work. I'm going to dl these and check 'em out soon, it all looks supremely useful!

    - m

  • djdonovan October 30th, 2007 at 9:16 am #2

    Thanks man! Yes let me know how you make out with it.

    And I promise next on my list is a posting on GO :)

    D

  • Jesse October 30th, 2007 at 3:38 pm #3

    What about XML and CSS loading? How hard would that be to add?

  • djdonovan October 30th, 2007 at 4:59 pm #4

    That's a great idea Jesse, something I will definitely look into adding. However, I would say 99% of my workflow requires that I load an XML first, with the path to the CSS in the XML file., then load the CSS, then I run the QueueLoader as the items I need to load using QueueLoader are in the XML file. Because of that, I guess I never thought to include those file types:)

    I can very easily add it in there, but if you wanted to store assets in an XML to be loaded with QueueLoader you would need to run a seperate QueueLoader (with the way it's set up now), which might add extra over head when you can use a simple XML loader.

    I actually made a post with the source for these files here.

    Thanks! :)

  • Jesse October 30th, 2007 at 6:53 pm #5

    THANKS! That was a very quick reply and I'm surprised to have inspired a new post. BTW – QueueLoader rocks!

    As far as loading XML and CSS first, I agree and do the same, but… I hate having to divide the steps for a total progress. That is the beauty of QueueLoader. Regardless of a site's structure, XML and CSS still feel like very good candidates for QueueLoader items.

    I went ahead and tried to see how hard it might be to add XML, and it was pretty straight forward.

    The only hitch I ran into was if the xml was mistyped the queue would just stop loading. That leads me into my next suggestion which would be a backup plan for failed loads.

    I switch a private method to public and bypassed the issue with:

    In queueloader.fla|onItemError() added:
    _oLoader.loadNextItem();

    Then I tried adding more images than were available. Increasing the number from 7 to 12 reported the Queue Progress as 62% when complete. I can see a scenario where if loading a gallery of images, and if one fails, I don't want the user to know.

    It might be nice get an option to output % of the total loaded vs. % of successful loads.

    Anyway, here is some quick code I added to include XML;

    In queueloader.fla|loadImages() added:

    _oLoader.addItem( prefix("") + "flashassets/xml/site.xml", new XML(), {title:"XML!!" });

    In QueueLoader.as|loadNextItem() added:

    case FILE_XML:
    trace("External XML");
    _URLLoader = new URLLoader();
    _URLLoader.addEventListener(Event.COMPLETE, completeHandler);
    _URLLoader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
    _URLLoader.addEventListener(ProgressEvent.PROGRESS, progressHandler);
    _URLLoader.load(request);
    break;

    In QueueLoader.as|completeHandler() added:

    if ( _currType == FILE_XML )
    {
    currItem.targ = new XML(event.target.data);
    }
    else if(_currType != FILE_AUDIO)
    {
    }

    In queueloader.fla|onItemInit() added:

    if ( event.filetype == QueueLoader.FILE_XML )
    {
    var xml = event.targ;
    trace( "xml: \n" + xml )
    }

    In queueloader.fla|onItemError() added:
    _oLoader.loadNextItem();

  • djdonovan October 30th, 2007 at 7:09 pm #6

    This all looks good Jesse. One thing I ask is you don't make load next item public:) Reason being, there is a very easy way to bypass failed loads with setting the second argument to true;


    var _oLoader:QueueLoader = new QueueLoader(true, addedDefinitions);

    But feel free to use it however you want:) Might be a few days before I can add these updates

  • Jesse October 30th, 2007 at 9:05 pm #7

    No, you're right – a private function is that way for a reason. I should have looked at the constructor. ;)

  • [...] QueueLoader AS3 rev 7 + Garbage Collection + SoundManager – Donovan [...]

  • Nick November 10th, 2007 at 4:59 pm #9

    Nice work, with css and xml loading this would be a killer.

    A few suggestions:

    * Add a method to prioritize or move objects up the que, this is a good thing to have when you have a que working in the background and you suddenly need to display certain elements as soon as possible.

    * Add a method to delete objects from the que.

    Thanks for sharing,

    Nick

  • djdonovan November 11th, 2007 at 1:01 am #10

    A new version has been posted!

Respond

get in on the action.

* Required

revatio efects buy lisinopril viagra order online erectile dysfunction medications I Need To Buy Viagra drugs on line cheap msm food allergies muscle building diet osteoporosis hormon ultram dosage levitra without prescription buy viagra in canada buy desyrel buy mexiletine buy phentermine online without prescription where to buy soma lithium carbonate women and viagra medications on line ultram er alprazolam no perscription viagra online without prescription type 2 diabetes diazepam pharmacology lower high blood pressure how to get big muscles discount dog products starlix buy deltasone health vitamins ultram dosage tooth whitening dentist buy pain meds now a reliever of arthritic pain hoodia patches cheap decadron reduce cholesterol naturally asthma control cheap generic viagra online fitness muscle online treatment for aids body building online course throat infection treatment increasing breast size naturally buy celebrex online buy antibiotics cheap online clomid testosterone booster patch nutritional diet for osteoporosis treating aids in africa blood pressure diet order vitamins order viagra online cymbalta vs lexapro xanax without prescription cheap pet health care buy prevacid buy prevacid soma 250 drug for nausea where to buy soma natural cure for erectile dysfunction ear pain right side back pain dog calming pills ordering viagra dental antibiotics antifungal strategies help the pain januvia cheap diabetes type 2 bronchitis diarrhea cimetidine dose alprazolam acne tips blood pressure buy cheap tooth whitening product prevacid online water pill buspirone dosage prescription phentermine buy beconase lower leg pain vitamins for women new antibiotic drug dog health care weight loss after baby skin cancer treatments high blood pressure yerba diet self help alcoholism benicar generic cure blood clot eye infections in dogs bph prostate family pharmacy zyban pharmacy atarax generic high blood pressure drug list buy xanax online buy natural antibiotics list how to white teeth avalide generic viagra cialis levitra medician for heart attacks phentermine prescription alcoholism new treatment help for depression heart failure medicine buy retin a buy levitra online with fast delivery body fat lose weight loss web sites buy nimotop herpes simplex new blood pressure drug how do a stop smoking flu shots herpes treatment enhance sexual performance effects of celexa viagra shop increase male volume treatment for chest pain cats bladder side effects clomid face wrinkles allegra klonopin effects relieve joint pain drugs that relieve pain new cat products human parasite ultram dosing tab tramadol carb blocker medication to stop smoking order viagra online in germany anxiety info ambien viagra gel use of xanax for anxiety online drugs without prescription weight loss health health ambien online buy viagra online cheap alternative medicine cholesterol mestinon blood pressure meds treatment parkinsons disease buy viagra without prescription methocarbamol effects pet health care information what is saw palmetto buy cialis online without a prescription flu drugs celebrex information gout cures buy orlistat on line sildenafil dosage blood pressure medication names ultram dosing order viagra canadian drug online big muscle fluconazole 150mg lasix cheap ashwagandha dosage side effects of ativan body acne treatment buying viagra online without prescription body building programs cat health care natural pet products viagra order body building tips high blood calcium level estradiol pill tips for weight loss back pain medications atenolol withdrawal vermox xanax dose antibiotics bronchitis cialis cialis information how to white teeth diabetes blood sugar levels pravastatin sleep disorders remedy viagra superactive diet pills hypnotherapy cds viagra cheep carisoprodol purchase cat anxiety buy alcoholism medications nausea cure how do a stop smoking relieve joint pain oral ketoconazole clonazepam pharma california cold flu calcium channel blocker hypertension prednisone allergy Cealis Lavetra effects of levitra professional anti allergic drug drugs for hiv body building online course dog ear problem super flu quickly stop smoking bad body odor atlas rx viagra abilify 10mg nolvadex 20mg hair loss treatment uk anti obesity chloramphenicol triphala sleep disorder treatment information on ambien remedy for hair loss when are beta blockers prescribed myasthenia gravis risperdal anxiety symptoms high blood pressure cure snoring chronic heart failure medicines valium with no prescription buy alcoholism medications generic pain medication alternative treatment arthritis diovan prescription latest diet pill effects of levitra professional clomid drug xanax without prescription online hair loss for men purchase viagra online hair loss products for men lamictal viagra online usa xenical no prescription pneumonia vs bronchitis prednisone 10 mg diflucan buy celebrex online anti fungus products endep liver infection treatment order indomethacin penis enlagement augmentin medication hair loss prevention treatment for yeast infection pyridium chest pain symptoms flovent generic valium with no prescription prevention of diabetes breast enhancement new york levitra do for men ginkgo biloba prescription lipitor klonopin zoloft order medication to aid in sleeping diabetes type 2 medicines for insomnia weight loss and fitness high blood pressure info purchase levitra online cialis on line health support discount prescription medications alprazolam no perscription how to purchase cialis acne free antifungal sinus women insomnia valium maximum dosage osteoporosis bone health buspar online discount cialis levitra viagra cure bronchitis prostate cancer treatment protonix overactive bladder medications skin cancer treatment effects klonopin yeast infection remedies fluconazole interaction canada online pharmacy viagra healthy women's vitamins expected weight loss with phentermine how to purchase cialis about cialis body building buy product how to buy cialis male erectile dysfunction femara drug topamax parkinson medications male bladder problems diabetes health care system haldol medication withdrawal zyrtec buy hyzaar cat hairball remedies cheap florinef lipitor use drugs for pain celebrex cealis lavetra Viagra Cialis Levitra buy nimotop how to increase fertility buy pain medicine online insomnia sleep problems cheapest place buy viagra online tooth whitening systems haldol medication information on levitra cialis advice bactroban price of drugs seroquel for anxiety malaria preventative effects of allegra body building info vytorin generic bladder problem solutions dog health help cialis cheap no prescription beta blockers bronchitis antibiotics back pain anti-fungal natural arthritis cures buying viagra online in britain penis development cheapest generic cialis snoring woman stretch penis purchase generic viagra virility gum viagra and sports buy proscar soma on line diet supplements that work breast enhancer pills how to enlarge breast buy cialis generic online dog bowel problems pet health information enhance breast acai alpha blocker medications cialis best on-line drugstore infection dog ears enhance sexual performance weight loss male sexual power cat health info clean dogs ears ultram used for gout medicines effective weight loss program improve sexual confidence cialis levitra viagra sildenafil kamagra cat skin disorders female sexual enhancement creams prozac on line bentyl drug diarrhea in pregnancy insomnia pills helping high blood pressure buy plendil lipitor use weight loss support group online buy plan b remedies for stomach ulcers cancer cure phentermine with no perscription best weight loss products online pain doctors buy vitamin a breast enhancer how to build muscle generic abilify free pain pills by mail breast enhancement products prostate cancer support accupril cymbalta medication small penis ramipril capsules depression symptoms treatment penis enhansment blood pressure drug names herpes medications to buy free smoking treatment online carisoprodol lasix drug depression and anxiety buy griseofulvin without prescription free weight loss tips klonopin pill viagra cialis levitra diet drug online enhancement breast atacand generic get viagra prescription online verapamil drug zyban what is hoodia overactive bladder in men buy tramadol cheap treatment for chronic fungal infection zoloft buy white spots on face pediatric diarrhea paxil information buy online cialis weight loss doctor online brain cancer treatment new weight loss drug levitra pro medication for depression relieve joint pain naturally enhancement breast health information bone health general drugs for hiv nexium drug premature ejaculation cure promethazine tablets treatment for dry skin erectile dysfunction cure online viagra without prescription best weight loss solutions drug allergies buy buy cialis online now cancer drug acessrx buy tooth whitening products parkinson disease medicine free hoodia