DEV Community

David Ortinau for .NET

Posted on

7

Infinite Scrolling with Incremental Data Loading in Xamarin.Forms

CollectionView has the built-in ability to fetch additional data when the user scrolls through the content already loaded. As the data threshold is met, like when only 4 items remain to be displayed, the CollectionView can execute a command to fetch more data and append.

public class FlightResultsViewModel : BaseViewModel
{
public Command LoadMoreFlightsCommand { get; set; }
public FlightResultsViewModel()
{
LoadMoreFlightsCommand = new Command(LoadMoreAsync);
InitData();
}
private async void LoadMoreAsync()
{
if (IsBusy)
return;
IsBusy = true;
await Task.Delay(1000); // Fake and API call delay
FlightsToDisplay.AddRange(
Flights.Skip(batchSize * currentFlightIndex).Take(batchSize)
);
currentFlightIndex += batchSize;
IsBusy = false;
}
public List<Flight> Flights { get; set; }
public List<Flight> FlightsEmpty { get; set; } = new List<Flight>();
public ObservableRangeCollection<Flight> FlightsToDisplay { get => flightsToDisplay;
set => SetProperty(ref flightsToDisplay, value); }
Random random = new Random();
private void InitData()
{
Flights = new List<Flight>();
for (var i = 1; i <= 1000; i++)
{
Flights.Add(new Flight
{
From = cities[random.Next(cities.Length - 1)],
To = cities[random.Next(cities.Length - 1)],
DepartDateTime = departDates[random.Next(departDates.Length - 1)],
ArrivalDateTime = arrivalDates[random.Next(arrivalDates.Length - 1)],
Price = prices[random.Next(prices.Length - 1)]
});
}
FlightsToDisplay = new ObservableRangeCollection<Flight>(Flights.Take(batchSize).ToList());
}
}

Check it out:

Resources:

GitHub logo davidortinau / FlyMe

Xamarin.Forms demo for 3 sessions presented at Microsoft Ignite 2019

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay