Xamarin-FreshMVVM Init not working in async way

632 views Asked by At

It's a Xamarin application and I am trying to call an async method inside the Init implemented in FreshMVVM, but doesn't seems to work.

When I load the page the ListView is empty, although bindings are correct. In fact, if I remove the await calls putting some int constants, ListView is shown correctly.

public class MainPageModel : BasePageModel
{
    private IService _service;
    public List<ModeMenuItem> List { get; set; }

    public MainPageModel(IService Service)
    {
        _service = Service;
    }

    public override async void Init(object initData)
    {
        base.Init(initData);

        List = new List<ModeMenuItem>()
        {
            new ModeMenuItem()
            {
                Name ="Test 1",
                Image ="\uE7EE",
                ViewModelType =null,
                TotalRequests = await _service.Count()
            },
            new ModeMenuItem()
            {
                Name ="Test 2",
                Image ="\uE913",
                ViewModelType =null,
                TotalRequests =await _service.Count()
            },
            new ModeMenuItem()
            {
                Name ="Test 3",
                Image ="\uE8CF",
                ViewModelType =null
            }
        };
    }
}
1

There are 1 answers

1
Cheesebaron On BEST ANSWER

Since you are delaying population and initialization of your data you provide to the ListView you need to either:

  1. Implement INotifyPropertyChanged on your ViewModel and fire it when you create your List property.
  2. Make your List an ObservableCollection and have it instantiated in the constructor of the ViewModel, then just populate it at a later point of time.

You can also mix the two.

So option 1. would be to just raise the PropertyChanged event:

private List<ModeMenuItem> _list;
public List<ModeMenuItem> List 
{ 
    get => _list; 
    set
    {
        _list = value;
        RaisePropertyChanged();
    }
}

Option 2. would be:

public ObservableCollection<ModeMenuItem> List { get; } 
    = new ObservableCollection<ModeMenuItem>();

and then popluate it without newing up a new collection:

List.Add();