Keep ViewModels with fragment volume in rotating screen

We are using libs support v 25.+

and new architecture components v 1.0.0-alpha3

, and we have recognized that ViewModels that are in the Fragment scope are not saved correctly:

class MyFragment : LifecycleFragment() {

    protected lateinit var viewModel: MyViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
    }
}  

      

The ViewModel is basically recreated every time the app is rotated. This can be solved by changing the value to onActivityCreated

used in Google examples. Since the documentation states usage onCreate

, I expect this to be a snippet or a bug ViewModelProvider

.

+3


source to share


1 answer


After consulting with the Android team, we found out that this is indeed a problem in SupportFragmentManager

, which is solved in v 26.+

, so the transition to

26.0.0-beta2

      



and now the ViewModels are being saved onCreate

as expected.

+2


source







All Articles