URLRequestBuffer – Buffer Your URLRequests

Let’s suppose your app makes a lot of http requests at once, and you need a good administration for that. Based on used browser your app is running on, you are only allowed to limited request count – mostly its 2 requests per domain, the remaining ones are sitting in browser buffer waiting to finish those actual. URLRequestBuffer is handy class that lets you manage URLRequest-s. E.g. you are creating image gallery and request hundreds of images in gallery at a time, now when user navigates throug the images you need to make some request more prioritized before others, some to be canceled, some may timeout etc. Here comes URLRequestBuffer in scene.

Pushing requests into the buffer automaticaly sorts requests by priority and tries to load next request based on priority/delay logic. After request is complete (timeouted, or error) it loads next and so on. Usage is very simple once you get familiar with 3 classes it consist of (URLRequestBuffer, URLRequestBufferItem and URLRequestBufferEvent)

// define buffer and max simultaneous (active) requests
var buffer:URLRequestBuffer = new URLRequestBuffer(2);

// loader - URLLoader or Loader instance
// request - URLRequest instance
// priority - uint, higher priority requests loads first
// delay - request is called after X milliseconds after pushing
// pushing requests into buffer returns URLRequestBufferItem, next suitable requests called
var bufferItem:URLRequestBufferItem = buffer.push(loader, request, priority, delay);
var bufferId:uint = bufferItem.id;

// URLRequestBufferItem by bufferId

// stop and trash request (buffered or active)

// enumerating waiting item list
for(var i:uint = 0; i < buffer.countWaiting; i++)
    bufferItem = buffer.getWaitingItem(i);

// enumerating active item list
for(var i:uint = 0; i < buffer.countActive; i++)
    bufferItem = buffer.getActiveItem(i);

// buffer event handling
buffer.addEventListener(URLRequestBufferEvent.WAITING_REQUEST_ADDED, onBufferChange);
buffer.addEventListener(URLRequestBufferEvent.WAITING_REQUEST_REMOVED, onBufferChange);
buffer.addEventListener(URLRequestBufferEvent.ACTIVE_REQUEST_ADDED, onBufferChange);
buffer.addEventListener(URLRequestBufferEvent.ACTIVE_REQUEST_REMOVED, onBufferChange);
buffer.addEventListener(URLRequestBufferEvent.REQUEST_TIMEOUT, onBufferChange);

private function onBufferChange(event:URLRequestBufferEvent):void
    var bufferItem:URLRequestBufferItem = event.item;
    // some stats
    trace(buffer.countWaiting, buffer.countActive)

2 comments so far

  1. MaRmAR June 2, 2010 21:43

    Thnx, URLRequestBuffer sa bude hodit 🙂

  2. Enrique June 20, 2010 03:52

    I have not tested it yet, but it looks really good, thanks for sharing !!!

Leave a comment

Please be polite and on topic. Your e-mail will never be published.