I have an external event that changes several fragments state, As I am using Android architecture components I've created several ModelViews for every fragment.
What is the right way to send messages between ModelViews
I have an external event that changes several fragments state, As I am using Android architecture components I've created several ModelViews for every fragment.
What is the right way to send messages between ModelViews
I am assuming you are using viewModel to preserve state across activity and fragment recreations. You do realize that a viewModel is essentially your model class, right? So why would you want to send messages between viewModels?
If you have an external event that changes a fragment's state, you should propagate it to your activities who will then send those message to your fragments where you can update your view model's state.
You should use one ViewModel in your activity for your event. You can then observe this view model from your activity and other fragments.
For example, below ViewModel class can wrap your event
public class SharedViewModel extends ViewModel {
private final MutableLiveData<Item> selected = new MutableLiveData<Item>();
public void select(Item item) {
selected.setValue(item);
}
public LiveData<Item> getSelected() {
return selected;
}
}
Then you can subscribe to changes to your event in different fragments like below:
public class DetailFragment extends LifecycleFragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedViewModel model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
model.getSelected().observe(this, { item ->
// update UI
});
}
}
Once subscribed, you can now make changes to your event data which will notify the observing fragments or activity:
public class MasterFragment extends Fragment {
private SharedViewModel model;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
itemSelector.setOnClickListener(item -> {
model.select(item);
});
}
}
Take a look at sharing data between fragments. Google documentation on android architecture components is limited but good.