Reputation: 4637
We are using support libs v 25.+
and the new architecture components v 1.0.0-alpha3
and we recognized that the ViewModels that are Fragment scoped are not correctly retained:
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 single time the app rotates. This can be solved by changing to onActivityCreated
as used in the google examples.
Since the documentation points out to use onCreate
I expect this is a fragment or ViewModelProvider
bug.
Upvotes: 4
Views: 672
Reputation: 4637
After consulting with the Android team we figured out that it is indeed an issue within the SupportFragmentManager
which is solved in v 26.+
so switching to
26.0.0-beta2
helped and now ViewModels are retained in onCreate
as expected.
Upvotes: 2