Search code examples
c#androidxamarin.androidmvvmcross

Init method is not called in Fragment view model


I have a fragment where in the init method I'm trying to show some data, But it is not getting.

namespace MoneyCare.Core.ViewModels
{
    public class HomeViewModel : MvxViewModel
    {
        public FirstViewModel First {
            get;
            set;
        }
        public SecondViewModel Second {
            get;
            set;
        }
        public ThirdViewModel Third {
            get;
            set;
        }
        public HomeViewModel()
        {
            First = new FirstViewModel();
            Second = new SecondViewModel();
            Third = new ThirdViewModel();
        }
    }

}

I have three fragments in my project.

namespace MoneyCare.Core.ViewModels
{
    public class FirstViewModel: MvxViewModel
    {
        Friend _friend;
        public List<Friend> AllFriends {
            get;
            set;
        }
        public string FriendUserName
        {
            get {
                return _friend.FriendUserName;
            }
            set
            {
                _friend.FriendUserName = value;
                RaisePropertyChanged(() => FriendUserName);
            }
        }
        public void Init()
        {
            Task<List<Friend>> result = Mvx.Resolve<Repository>().getFriendsList();
            result.Wait();
            AllFriends = result.Result;
        }
        public ICommand check
        {
            get
            {
                return new MvxCommand(() =>
                {
                    //Task<List<Friend>> result = Mvx.Resolve<Repository>().getFriendsList();
                    //result.Wait();
                    //AllFriends = result.Result;
                    ShowViewModel<CheckViewModel>();
                });
            }
        }
        //Opens Add Friends Activity
        public ICommand OpenAddFriend
        {
            get
            {
                return new MvxCommand(() => ShowViewModel<AddFriendViewModel>());
            }
        }
    }

}

I tried the same thing with Activity, For checkview activity, it is working but not for Fragment.


Solution

  • The ViewModel's lifecycles are not being executed because you're not loading them with MvvmCross, you're just constructing them as you would ordinary .NET classes. Only the constructor will actually run. If you want Init to execute, you need to load the ViewModel with MvvmCross, which is typically done by navigating to it with ShowViewModel<YourViewModel>.

    Fragments being contained by activities in Android doesn't mean that your ViewModels need to be children of your HomeViewModel. Calling ShowViewModel<FirstViewModel> will ensure that FirstViewModel's Initfires.