I made a scrolling app with CollectionView with ItemSource=Photos
and after sometime scrolling the app got freezed.
This is my ViewModel
counstructor code with all elements:
public MainPageViewModel()
{
CounterData = 20;
StandartCounter = 20;
LoadPhotosCommand = new Command(execute: async () => await ExecuteGetAllPhotos());
LoadRefreshCommand = new Command(execute: async () => await ExecuteRefreshGetAllPhotos());
LoadNewPhotosCommand = new Command(execute: async () => await ExecuteGetNewPhotos());
LoadSelectedPhotoCommand = new Command(execute: async () => await ExecuteGetDetailsSelectedPhoto());
Photos = new ObservableCollection<Photo>();
PhotosAll = new ObservableCollection<Photo>();
PhotosModel = new PhotosModel();
SelectedPhoto = new Photo();
}
This is my logic in the ViewModel
, and this function get all photos from the API - store them in the PhotosAll
list and add 20 elements to Photos
list which is ItemSource of the collectionView:
async Task ExecuteGetAllPhotos()
{
if (IsBusy)
return;
try
{
IsBusy = true;
Photos.Clear();
PhotosAll.Clear();
PhotosModel = await InstagramCloneDataStore.GetAllPhotos();
if (PhotosModel != null)
{
foreach (var photo in PhotosModel.Photos)
{
PhotosAll.Add(photo);
}
foreach (var el in PhotosAll.Skip(0).Take(StandartCounter))
{
Photos.Add(el);
}
CounterData = StandartCounter;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
var msg = ex.Message;
}
finally
{
IsBusy = false;
}
}
This is the function from the RemainingItemsThresholdReachedCommand
and the logic is when user reach scrolling 20 items read new 20 items and add them to Photos
list.
async Task ExecuteGetNewPhotos()
{
if (IsBusy)
return;
try
{
IsBusy = true;
await Task.Delay(100);
foreach (var el in PhotosAll.Skip(CounterData).Take(StandartCounter))
{
Photos.Add(el);
}
CounterData += StandartCounter;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
var msg = ex.Message;
}
finally
{
IsBusy = false;
}
}
First started to scrolling verywell but after sometime the application got freezed. Does anyone have the same problem? Or have some solution for this?
UPDATE
It looks like Photos
list look bigger the loading new items getting slow
After hours of reviewing my code i learn 2 things:
StandartCounter
, and one value for count the current element position in the big List i caled RailCounter
.
In every turn u read from PhotosAll.Skip(RailCounter).Take(StandartCounter)
and
RailCounter += StandartCounter;
The problem was CounterData must be static!