On-demand loading is a common technique in mobile apps where data is loaded in chunks as the user scrolls down a list in real time. If you’ve ever searched for something to buy on the Amazon shopping app, then you’ve seen on-demand loading. It’s ideal for mobile apps because downloading data conservatively improves app performance, and users prefer downloading only what they need. In the development world, it’s also known as incremental loading. If you’re developing a mobile app using Xamarin.Forms, you’ll find that on-demand loading is not supported for free—you have to implement it yourself.

Here, we’ll show you how to use the ComponentOne CollectionView for Xamarin to provide on-demand loading for the Xamarin.Forms ListView control.

How to Perform On-Demand Loading with the Xamarin.Forms ListView

Adding on-demand loading to ListView is accomplished in two basic steps:

  1. Implement your own collection view class that extends a C1CursorCollectionView and overrides GetPageAsync. This is where we’ll provide our logic that loads the data in chunks or pages.
  2. Extend ListView and listen to the ItemAppearing event. This determines when the user has reached the bottom of the ListView

Next, let’s cover both steps in more detail.

Extending C1CursorCollectionView

The C1CursorCollectionView is the base class for adding cursor-like, incremental loading to a collection of items. It gets its name from the similarly named paging mechanism used by the Twitter API. It provides the helpful hooks to load data in “real time” as paged chunks. First, add the C1.CollectionView packages to your Xamarin.Forms app.

Right-click your solution and select Manage NuGet Packages for Solution. Then search or browse the list for C1.CollectionView. Click Install.

Incremental, On-Demand Loading with Xamarin.Forms ListView

The C1CollectionView is a portable class library , so it should work across all projects within your Xamarin.Forms solution. It contains multiple types of collection views. Create a new class that extends the C1CursorCollectionView base class. Here’s the bare bones implementation of this class and the GetPageAsync method.

**public** **class** MyOnDemandCollectionView : C1CursorCollectionView<MyDataItem>   
{   
    **protected** override async Task<Tuple<string, IReadOnlyList<MyDataItem>>> GetPageAsync(string pageToken, **int**? count = null)   
    {   
        // create new page of items   
        var newItems = **new** List<MyDataItem>();   
        **for**(**int** i = 0; i < count; i++)   
        {   
            newItems.Add(**new** MyDataItem(**this**.Count + i));   
        } 

        **return** **new** Tuple<string, IReadOnlyList<MyDataItem>>("token not used", newItems);   
    }   
} 

#xamarin.forms #mobile #.net

Incremental, On-Demand Loading with Xamarin.Forms ListView
4.40 GEEK