I see a couple of problems.
- C# does not support async constructor calls. Therefore calls made in a constructor (ctor) must be sync. This is by design. If
InitializeAsync
is only called here then there is no reason to make it async because that isn't supported. You must wait for the async call to complete before the ctor returns. Since you're using anObservableCollection
then this is fine because when the collection is eventually populated then the UX will get notified anyway.
public ReservationListingViewModel()
{
//This must be called sync, C# doesn't support async ctor calls
InitializeAsync().GetAwaiter().Wait();
}
Note however that if the method throws an exception then it'll be wrapped in AggregateException
which is confusing in a ctor call so you might need to wrap the call in a handler. Calling async methods synchronously is generally not recommended.
-
GetReservations
is creating a new object and storing it in the field that the class is using. So as soon as the call starts you just stomped over your previous values. TheInitializeAsync
method technically does nothing. It takes the return value of the method (which is the value of_reservations
) and stores it back into itself. YourGetReservations
method should create and store the new collection in a temp variable. Then return the temp variable from the method. TheInitializeAsync
method can then assign it to the field, optionally after it does any post retrieval work. -
_reservations
is readonly. That means its value can only be set in the constructor, not any other method. So the assignment inIntializeAsync
(andGetReservations
) is not allowed. In general fields should be readonly if they shouldn't change. In this case you're changing a field after creation so it cannot be readonly. Remove the modifier. In general it is not a good idea to wipe a field after you've set it up since anyone watching that original value would miss the changes. Since you're usingIEnumerable
here that isn't an issue but if you were to ever switch the property toObservableCollection
so you actually gain the benefit of using that type then code tied to the original field won't suddenly recognize a new field because they are using the original value instead.
So rather than creating a new observable collection each time, you should create it readonly, get the new values and then clear the original collection and add the new values in. Something like this perhaps.
public async Task InitializeAsync ()
{
var newItems = await GetReservations();
//Clear original values
_reservations.Clear();
foreach (var item in newItems)
_reservations.Add(item);
}
Note that this is going to trigger a lot of change notifications so you might want to "disable" any UX updates until you're done.