Search code examples
androidkotlinandroid-architecture-components

Retain ViewModels with fragment scope while rotating screen


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.


Solution

  • 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.