AppCompatActivity VieModelStoreOwner

Anton Oosthuizen 1 Reputation point
2021-02-15T18:58:34.767+00:00

I'm a bit lost, I am trying to implement the ViewModelProvider in Xamarin.Android but it seems like IViewModelStoreOwner is not implemented by AppCompatActivity

C# Code

 var androidViewModelFactory = ViewModelProvider.AndroidViewModelFactory.GetInstance(Application);


                var viewmodelprovider =
                    new ViewModelProvider(this, androidViewModelFactory); **// this=AppCompatActivity does not impliment IViewModelStoreOwner** 

                var vm = (CameraXViewModel)viewmodelprovider.Get(cameraXViewModel.Class);

Java Code

 new ViewModelProvider(this,androidViewModelFactory ) /**/ this =AppCompatActivity javacode implimenents ViewModelStoreOwner Interface**   
        .get(CameraXViewModel.class)
        .getProcessCameraProvider()
        .observe(
            this,
            provider -> {
              cameraProvider = provider;
              if (allPermissionsGranted()) {
                bindAllCameraUseCases();
              }
            });

Therefore I cannot implement ViewModelProvider in Xamarin.Android

What am I missing.

Thanks in advace

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,354 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Junior Jiang-MSFT 11 Reputation points
    2021-02-16T09:21:01.753+00:00

    Hello,

    Welcome to Microsoft Q&A!

    In Xamarin Android, FormsAppCompatActivity already contain the ViewModelStore method . It is the same effect with Native Android ViewModelStoreOwner to get ViewModelStore.

    Here it the native ViewModelStoreOwner class:

    public interface ViewModelStoreOwner {  
        /**  
         * Returns owned {@link ViewModelStore}  
         *  
         * @return a {@code ViewModelStore}  
         */  
        @NonNull  
        ViewModelStore getViewModelStore();  
    }  
    

    In Xamarin Android, you could write code as follows below FormsAppCompatActivity class:

    public override ViewModelStore ViewModelStore => base.ViewModelStore;  
    

    Then you also will get the ViewModelStore.

    Best Regards,

    Junior Jiang

    ----------

    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.