Reputation: 413
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
Upvotes: 0
Views: 863
Reputation: 8106
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.
Upvotes: 1