Tuesday, November 18, 2008

Lazily Loading List Items in Flex

When using Flex controls with a large dataset, it's often too expensive to load the items in the list all at once. In some scenarios you may find yourself using a third-party API which dictates that you use pagination by only allowing you to load a maximum number of elements at a time. In these scenarios, one of the more elegant solutions is to implement an IList that lazily loads items as they're requested.

I've implemented an example application which demonstrates two variants of this technique. The source is available via the normal right-click on the application mechanism, or via this link.

The first variant (in the first tab of the example application) immediately throws ItemPendingErrors when the list item hasn't previously been loaded. The flex framework supports asynchronous loading of items requested via the IList interface via ItemPendingError. Most Flex controls participate in the ItemPendingError contract, including List, HorizontalList, TileList, DataGrid, Menu, and Tree. When an IList (or ICollection) throws this error, the control gracefully handles it by registering a new IResponder with the error. The control's callback is called asynchronously when the results eventually are available, allowing the control to render the items as they become available.

The second variant (in the second tab of the example application) begins by synchronously returning partially loaded items to the List control, immediately requesting a page of details as the abbreviated version of each item is requested. The LazyList then replaces the appreviated version with the full version in the background, dispatching the appropriate CollectionEvent. The asynchronously dispatched CollectionEvents allow the control to render the details of the items as they become available.