Retain ViewModels with fragment scope while rotating screen

Viewed 642

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.

1 Answers
Related