Skip to content

On demand loading

ccapndave edited this page Feb 26, 2011 · 8 revisions

Flextrine supports on-demand loading both of entities and collections. By default these are both active, although you can disable them using the configuration of EntityManager. See The Entity Manager for more details.

Flex provides an error called ItemPendingError which is used to signify that some data is not yet available, but is being loaded from the server. In order to adhere to standards and not duplicate code unnecessarily Flextrine uses this error throughout its on-demand loading system.

Loading associated collections on-demand

A uninitalized collection will automatically initialize itself when something attempts to retrieve an element or to get its length. The collection will then throw an ItemPendingError which the application can attach IResponders to.

In fact, Flex 3 components are already set up to automatically handle ItemPendingErrors. In the following example, if the doc.patients collection is uninitialized the List will cause it to initialize, then once it has loaded the List will update with the loaded content.

<mx:List dataProvider="{doc.patients}" />

In Flex 4 components don't automatically handle ItemPendingErrors, and you need to use the new AsyncListView wrapper around the data provider:

<s:List dataProvider="{new AsyncListView(doc.patients)}" />

Loading entities on-demand

If a property of an uninitialized entity is accessed, Flextrine will automatically try and load the entity. The mechanics of normal databinding will cause any components displaying the entity's data to update once the entity has initialized. There should be no extra work to do here.

On-demand loading in AS3

This system works very well in MXML, which is setup to handle ItemPendingErrors. However, when coding in AS3 instead of MXML it becomes necessary to handle ItemPendingErrors yourself:

try {
	firstPage = book.pages.getItemAt(0) as Page;
} catch (e:ItemPendingError) {
	e.addResponder(
		new AsyncResponder(
			function(e:ResultEvent, token:Object):void {
				firstPage = book.pages.getItemAt(0) as Page;
			},
			function(e:FaultEvent, token:Object):void {
				// Do something on a fault
			}
		)
	);
}

I found this code snippet quite annoying to write and maintain, so Flextrine provides a handy method which wraps this code in a neater call.

LazyUtil.async(
	function():void {
		firstPage = book.pages.getItemAt(0) as Page;
	},
	function():void {
		// Do something on a fault
	}
);

In fact, the same effect could be achieved in AS3 using the requireOne and requireMany methods of EntityManager. However, if you are coding using an MVC framework such as PureMVC or Robotlegs you will often not want the view components to have knowledge of EntityManager, which is when ItemPendingError and LazyUtil.async come in useful.