英文:
Instantiation of SharedViewModel
问题
I follow the coding in Flow tutorials. In one of them (communication between 2 fragments with a shared ViewModel), there is a deprecated method ViewModelProviders.of(...)
:
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
viewModel = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
viewModel.getText().observe(getViewLifecycleOwner(), new Observer<CharSequence>() {
@Override
public void onChanged(@Nullable CharSequence charSequence) {
editText.setText(charSequence);
}
});
}
The author explained that the app knows when to destroy and recreate the ViewModel, so we shouldn't do it. I found a method which replaces the deprecated ViewModelProviders
:
// myNewMethod
viewModel = ViewModelProvider.AndroidViewModelFactory.getInstance(getActivity().getApplication()).create(SharedViewModel.class);
The problem is now that this method always creates a new instance of Shared ViewModel. So when I have two fragments, the method is called twice and generates two different shared ViewModels!
How to get rid of this, and where should I instantiate the Shared ViewModel? Main activity or still in the fragment?
英文:
i follow the coding in Flow tutorials. In one of them (communication between 2 fragments with shared ViewModel there is a depracated method ViewModelProviders.of(...:
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
viewModel = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
viewModel.getText().observe(getViewLifecycleOwner(), new Observer<CharSequence>() {
@Override
public void onChanged(@Nullable CharSequence charSequence) {
editText.setText(charSequence);
}
});
}
The author explained that app knows when to destroy and recreate ViewModel so we shouldn't do it. I found a method which replaces the depracated ViewModelProviders:
//myNewMethod
viewModel= ViewModelProvider.AndroidViewModelFactory.getInstance(getActivity().getApplication()).create(SharedViewModel.class);
The problem is now, that this method create always a new instance of Shared ViewModel. So when i have two fragments, the method is called twice and generate two different shared ViewModels !
how to get rid of this and where should i instantiate the Shared ViewModel ? Main acitvity or still in fragment?
答案1
得分: 2
问题已解决。我应该使用 ViewModel 而不是 AndroidViewModel,并使用以下方式实例化:
ViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
英文:
Problem solved. I should use ViewModel instead of AndroidViewModel And instantiate with :
ViewModel= new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论