I’m having what I believe is a timing issue with model binding when a .NET MAUI page opens. I have a Page with a Picker and the binding is working fine at times. To get the data for the ItemsSource, I’m using the ‘OnAppearing’ event to call a Command on the View Model that is an async method. This in turn calls an internal service object that calls an external API asynchronously.
Now I believe the main reason it works sometimes, is I cache the results from the API in my internal service class for 10 minutes as this data won’t change that often. So usually the first call doesn’t complete in time, but it’ll work the next time.
Sometimes the timing works, and other times it doesn’t.
Here’s the View Model Command:
public async Task InitializeForm()
{
IsBusy = true;
Title = "Project Information";
var contractorList = await _contractorService.GetActiveContractors();
ContractorListDTO notListedContractor = new ContractorListDTO()
{
Id = Guid.Empty,
FirstName = "Not",
LastName = "Listed"
};
ContractorListDTO blankContractor = new ContractorListDTO()
{
Id = Guid.NewGuid(),
FirstName = "",
LastName = ""
};
ContractorList = contractorList.Where(e => e.ContractorType != ContractorType.Designer).ToList();
ContractorList.Add(notListedContractor);
ContractorList.Insert(0, blankContractor);
SelectedContractor = blankContractor.Id;
IsBusy = false;
}
And here’s the method on the Contractor Service:
public async Task<List<ContractorListDTO>> GetActiveContractors()
{
if (cachedContractors.Count == 0 || cacheExpiration < DateTime.Now)
{
string address = "/api/contractor/getall";
var returnedItem = await GetDTOAsync<List<ContractorListDTO>>(_httpClient, address);
cachedContractors = returnedItem;
cacheExpiration = DateTime.Now.AddMinutes(10);
}
return cachedContractors;
}
While I have a general pattern going with the Task paradigm, it seems that the await isn’t waiting for the results of the service to return before final execution of the InitializeForm.
Thoughts?