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.


Mitch said...

This has been very informative, thanks!

What copyright applies to your sample code? Is it okay to use LazyList.as in other projects?

nvihinen said...

This is just sample code. Use freely at your own risk.

Squee-D said...

Cheers. Very useful and saves me a lot of digging around.

Shiva said...

Excellent and Useful Article!!

I tried using the IList with AdvancedDataGrid to simulate lazy loading of the data from back-end. Lazy loading works just fine but stops working once we try to sort or filter before the complete data is fetched. The moment you sort/filter, "toArray()" metod gets called. I modified IList.toArray() method to return itemCache. It did not help. Any ideas or suggestions? We are really in need of implementing it. Appreciate quick help.