Previous Page
Next Page

Recipe 19.4. Checking Load Progress

Problem

You want to know how much of the data has loaded.

Solution

Subscribe to the progress event of the URLLoader.

Discussion

The URLLoader class has a progress event that is dispatched whenever progress is made in downloading data. The Flash Player passes a flash.events.ProgressEvent instance to the event handler, allowing you to inspect the bytesLoaded and bytesTotal properties of the event. The bytesLoaded property contains the number of bytes that have been received so far. The bytesTotal property contains the total number of bytes in the file being loaded, or zero if the information is unknown.

The data is fully loaded when the bytesLoaded property of the ProgressEvent is the same as the bytesTotal property. However, this is usually not something you check in your progress event handler. Instead, listen for the complete event, which is dispatched when the data is fully loaded. See Recipes 19.1, 19.2, and 19.3 for examples of handling the complete event.

To check on the loading progress, use code like the following:

package {
  import flash.display.*;
  import flash.text.*;
  import flash.events.*
  import flash.net.*;
  
  public class CheckProgressExample extends Sprite {
    private var _output:TextField;
  
    public function CheckProgressExample(  ) {
      initializeOutput(  );
      loadData(  );
    }
    
    private function initializeOutput(  ):void {
      _output = new TextField( );
      _output.width = stage.stageWidth;
      _output.height = stage.stageHeight;
      
      addChild( _output );    
    }
    
    private function loadData(  ):void {
      var loader:URLLoader = new URLLoader(  );
      
      // Listen for the progress event to check download progress
      loader.addEventListener( ProgressEvent.PROGRESS, handleProgress );
      
      loader.load( new URLRequest( "example.txt" ) );
    }
    
    private function handleProgress( event:ProgressEvent ):void {
      // Calculate the percentage by multiplying the loaded-to-total 
      // ratio by 100
      var percent:Number = Math.round( event.bytesLoaded 
                                       / event.bytesTotal * 100 );
      
      _output.text = " Loaded: " + event.bytesLoaded + "\n"
                        + "  Total: " + event.bytesTotal + "\n"
                        + "Percent: " + percent;
    }
  }
}

In practice, it's fairly unlikely that you'll need to actually monitor the loading of data via the progress event. It is only plausibly necessary in cases of very large amounts of data being downloaded.

When using URLLoader, you cannot read the data while the download is in progress. The progress event is simply a notification of download progress because of this behavior. To access the data as it downloads, use URLStream, as discussed in Recipe 19.5.

See Also

Recipes 19.1, 19.2, 19.3, and 19.5


Previous Page
Next Page
Converted from CHM to HTML with chm2web Pro 2.85 (unicode)