Skip to content

Instantly share code, notes, and snippets.

@rezaiyan
Last active November 11, 2019 08:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rezaiyan/20da37f93cac6305e495f277f8d5a338 to your computer and use it in GitHub Desktop.
Save rezaiyan/20da37f93cac6305e495f277f8d5a338 to your computer and use it in GitHub Desktop.
This is a simple example of a shared viewmodel
class SharedViewModel extends ViewModel {
public MutableLiveData<String> liveData = new MutableLiveData<>();
}
class parentFragment {
sharedVm = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
sharedVm.liveData.observe(this, new Observer<String>() {
@Override
public void onChanged(String stringValue) {
myTextView.setText(stringValue);
}
});
}
class childFragment1 {
sharedVm = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
sharedVm.liveData.setValue("text1");
}
class childFragment2 {
sharedVm = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
sharedVm.liveData.setValue("text2");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment