I have a problem. I created this ViewModel for my CollectionView:
public class TemplateListViewModel
{
public double WidthHeight { get; set; }
public ICommand LoadTemplates => new Command(MyHandler);
public int CurrentTemplateCountReceived;
public bool HitBottomOfList = false;
public ObservableCollection<TemplateSource> sourceList { get; set; }
public TemplateListViewModel()
{
CurrentTemplateCountReceived = 0;
sourceList = new ObservableCollection<TemplateSource>();
var mainDisplayInfo = DeviceDisplay.MainDisplayInfo;
var width = mainDisplayInfo.Width;
var density = mainDisplayInfo.Density;
var ScaledWidth = width / density;
WidthHeight = (ScaledWidth / 2);
loadingTemplates += onLoadingTemplates;
LoadTemplateList();
}
private event EventHandler loadingTemplates = delegate { };
private Task LoadTemplateList()
{
loadingTemplates(this, EventArgs.Empty);
return null;
}
private async void onLoadingTemplates(object sender, EventArgs args)
{
if (HitBottomOfList == false)
{
List<Template> templateList = await App.RestService.GetTemplates(App.User, CurrentTemplateCountReceived);
if (templateList != null)
{
foreach (var template in templateList)
{
ImageSource source = ImageSource.FromUri(new Uri("mysite.org/myapp/" + template.FileName));
TemplateSource templateSource = new TemplateSource { Id = template.Id, Source = source, WidthHeight = WidthHeight, FileName = template.FileName };
sourceList.Add(templateSource);
}
CurrentTemplateCountReceived = sourceList.Count;
}
else
{
HitBottomOfList = true;
}
}
}
bool handling = false;
public void MyHandler()
{
// already handling an event, ignore the new one
if (handling) return;
handling = true;
LoadTemplateList();
handling = false;
}
}
Now what this does is: It collects image locations from my webpage and then creates the ImageSources for those collected images and adds it to the sourceList. Now I also created a RemainingItemsThresholdReachedCommand="{Binding LoadTemplates}" in the xaml, so it collects more data when it almost hits the bottom of the CollectionView, by calling this command: ICommand LoadTemplates => new Command(MyHandler);. This event gets fired a lot of times so I created this handler:
public void MyHandler()
{
// already handling an event, ignore the new one
if (handling) return;
handling = true;
LoadTemplateList();
handling = false;
}
That checks if there is already an event being handled.
The problem is that in MyHandler, LoadTemplateList() doesn't get awaited for result, which results in many calls to my webpage, because handling will be set to false immediately!
Now how can I await the LoadTemplateList()?