NowBI / Xamarin-Forms-Mobile-Template

A simple Xamarin Forms project with a pre-configured Visual Studio 2015 environment, View Templates, Themes, Observables and Reactive Properties, Dependency Injection via Autofac, Unit Tests via xUnit, and Crash Logging via HockeyApp to be used as a starting point for mobile projects deployed to Android and iOS.
MIT License
81 stars 17 forks source link

Question: In ViewModel where/how use async initialization #2

Open Jerome2606 opened 6 years ago

Jerome2606 commented 6 years ago

Hello,

first of all thanks for your template. I'm looking into it and have a question:

In ShoppingViewModel in real world application, the items should be retrieve using async/await method. Like consuming API.

As async is not possible in constructor, how can I get around this ?

RoboCafaz commented 6 years ago

Two options:

If you want to use a Service pattern as we do you can create an async method in ShoppingItemService that service to fetch the data, then set the Value property of _inventoryInternal to the fetched data. Then it will automatically propagate to any existing or new versions of the ShoppingViewModel because ShoppingItems is derived from the Service's inventory.

Alternatively if you want to fetch the item set for every instance of ShoppingViewModel, you can initialize its list of items as a Reactive Property with an empty collection as the default value:

ShoppingItems = new ReactiveProperty<IEnumerable<ShoppingItemViewModel>>(Enumerable.Empty<ShoppingItemViewModel>());

Then you can create an async method to fetch the data and set ShoppingItems.Value to the result.

In either implementation the View should auto-update its list with the new data in the Reactive Property as it comes in.

Good luck!