简体   繁体   中英

android MVVM What's the right way to setViewModel to Fragment

I am practicing Google MVVM https://github.com/googlesamples/android-architecture/tree/todo-mvvm-databinding , having a problem of linking Fragment and ViewModel.

The google demo doing like this:

in Activity,

  1. Fragment.newInstance()
  2. new ViewModel()
  3. fragment.setViewModel(viewModel). (Implementing a setViewModel method in Fragment)
  4. viewmodel.loadingData() in fragment's onResume or onStart

My question is, this seems not safe. If due to some reason, system recycle fragment and recreate using default constructor, viewModel will be null ?

am I right or am I missing something?

As a workaround, I think put the new ViewModel() in Fragment's onCreateView method should be fine?

You should not create new instance of the ViewModel anywhere in Fragment or Activity . The correct way is to obtain the instance by using the ViewModelProviders and a ViewModelProvider.Factory

There are many article around the net about MVVM and ViewModel using dagger2 such as this or this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM