Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Android Jetpack's SavedStateViewModelFactory work?

my viewmodel-savestate version is
implementation 'androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-alpha03'

in version 1.0.0-alpha01 ,i can use

 MyViewModel myVM = new ViewModelProvider(this, new SavedStateVMFactory(this)).get(MyVM.class);

to create viewmodel with savestate, but in version 1.0.0-alpha03 ,

SavedStateVMFactory 

cant work , i need to use new SavedStateViewModelFactory but i dont konw what is the second params means, the code may look like this below:

        myVM = new ViewModelProvider(this, new SavedStateViewModelFactory(getApplication(),xxxxxxx)).get(MyVM.class);

and i cant find any document about this in android developer website, sad

like image 244
xizz Avatar asked Sep 08 '19 02:09

xizz


1 Answers

As per the SavedStateRegistryOwner documentation, both Fragment, and AppCompatActivity implement SavedStateRegistryOwner, so you can just pass in this:

 myVM = new ViewModelProvider(this,
     new SavedStateViewModelFactory(getApplication(), this))
     .get(MyVM.class);

Just make sure you're using AppCompat 1.1.0, which is when AppCompatActivity (and its base class, FragmentActivity and ComponentActivity) started to implement SavedStateRegistryOwner.

like image 87
ianhanniballake Avatar answered Oct 06 '22 09:10

ianhanniballake