Android MVVM: activity with multiple fragments - where to post shared livedata?

I have an architectural question about ViewModels androids:

Let's say that in my application I have activity with two fragments inside (using Viewpager). These two snippets do different things (why can they have their own ViewModel?), But they also need different data, similar.

This is, for example, a state if a network connection is available or not (and both fragments show different error interfaces if there is no connection), or some user settings that come through Push from the server and affect both fragments equally.

It looks something like this:

enter image description here

Now my question is how to deal with this situation when using ViewModels? Is it good that several ViewModels are observed in the view, as if I had a ViewModel for Activity (supporting a state that is the same) and one for each fragment, for example:

enter image description here

This has been outlined here , but this is not a good practice, since relationships in MVVM are usually

View n - 1 ViewModel n - 1 Model

But I'm not sure where is the right place for such a common LiveData in my case?

+7
android mvvm
source share
1 answer

I think the concept of ViewModel was that it should be associated with one " screen ", and not with the " View ". Therefore, based on this logic, I think you can use the same ViewModel if several fragments refer to the same ViewModel, because they technically belong to the same " Screen ".

In snippets, you can request activity for the ViewModel, which contains an instance of LiveData and can provide you with updates as needed.

Hope this answers your question.

Update: I found a link to a sample snippet in Google samples . Check the onCreateView () method. The code below is for reference:

@Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View root = inflater.inflate(R.layout.addtask_frag, container, false); if (mViewDataBinding == null) { mViewDataBinding = AddtaskFragBinding.bind(root); } mViewModel = AddEditTaskActivity.obtainViewModel(getActivity()); mViewDataBinding.setViewmodel(mViewModel); setHasOptionsMenu(true); setRetainInstance(false); return mViewDataBinding.getRoot(); } 

PS If you find the best solution / answer / practical, you know.

0
source share

All Articles