简体   繁体   中英

Access ViewModel when using MVVM pattern

I'm trying to implement the MVVM partern. So I have an Activity containing a ViewPager with 3 fragments in it. Each fragment works on the same entity.

Inside the Activty I have created an instance of the ViewModel like that.

protected void onCreate(Bundle savedInstanceState) {
    TaskViewModel.Factory factory = new 
    TaskViewModel.Factory(this.getApplication(), mTaskId);
    mTaskViewModel  = ViewModelProviders.of(this, factory).get(TaskViewModel.class);
}

Now what is the proper way to share it with the fragments ?

Is a getter / setter is still respecting the guidelines ?

Thanks

If you want to share the same ViewModel between your Fragments (ViewPager) you initialize your ViewModel using your activity instead of "this" (fragment).

The First parameter in "of" defines which LivecycleOwner will be used. Since you choose the activity the ViewModel will be persistent between the Fragments and stay alive until the activity has been destroyed. (Kotlin)

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
   var viewModel = ViewModelProviders.of(
                activity, //define who's the holder of the ViewModel
                viewModelFactory)
   .get(YourVm::class.java)
  /** ..... **/
}

The Factory itself is just used to initialize the ViewModel (with data).

Android Example:

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState) {
          YourVm viewModel = ViewModelProviders.of(
                getActivity(), //define who's the holder of the ViewModel
                viewModelFactory)
   .get(YourVm::class); 
  /** ... **/
}

That means that you can initialize/use your ViewModel in your activity and use ViewModelProviders.of() to get the persistent ViewModel.

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