英文:
Changing LiveData in Activity doesn't notify observer in child Fragment
问题
我试图在托管片段的活动中更新 LiveData 对象,然后我想在观察到它之后更新片段的 UI。问题是片段的 UI 仅在重新启动片段时更新。我该如何做才能实现在活动中的数据每次更改时,在片段中实时更新 UI 呢?
// 活动代码:
transactionViewModel = ViewModelProviders.of(this, providerFactory).get(TransactionViewModel.class);
transactionViewModel.getUserValues();
// 片段:
transactionViewModel = ViewModelProviders.of(getActivity(), providerFactory).get(TransactionViewModel.class);
viewModel.userValues.observe(getActivity(), userValues -> { if(userValues.data != null){} // 更新 UI });
英文:
I'm trying to update LiveData object in activity that hosts a fragment and then I want to update the fragment's UI after observing it. The problem is the fragment's ui only updates when fragment is restarted. What can I do to achievie real-time update of Ui in fragment every time the data changes in activity?
// Activity code:
transactionViewModel = ViewModelProviders.of(this, providerFactory).get(TransactionViewModel.class);
transactionViewModel.getUserValues();
/// Fragment:
transactionViewModel = ViewModelProviders.of(getActivity(), providerFactory).get(TransactionViewModel.class);
viewModel.userValues.observe(getActivity(), userValues -> { if(userValues.data != null){}//update the ui }
答案1
得分: 1
实现“实时更新UI”,我建议使用data-binding。
在你的代码中,我认为你正在观察一个不同的viewModel引用。
尝试在将你的Activity转换后进行观察(我这里使用的是Kotlin):
val myActivity = (requireActivity() as MainActivity)
myActivity.transactionViewModel.viewModel.userValues.observe(getActivity(), userValues -> {
if(userValues.data != null){} //更新UI
}
英文:
To achievie "real-time update of Ui" i sugesst using data-binding.
In your code, I think you are observing a deferent reference of viewModel.
Try observing after casting your activity(am using kotlin here):
val myActivity = (requireActivity() as MainActivity)
myActivity.transactionViewModel.viewModel.userValues.observe(getActivity(), userValues -> {
if(userValues.data != null){}//update the ui }
答案2
得分: 0
transactionViewModel = ViewModelProviders.of(getActivity(), providerFactory).get(TransactionViewModel.class);
// this goes in onViewCreated
viewModel.userValues.observe(viewLifecycleOwner, userValues -> {
if(userValues.data != null){
//update the ui
}
});
英文:
Fragment code
> transactionViewModel = ViewModelProviders.of(getActivity(), providerFactory).get(TransactionViewModel.class);
>
> viewModel.userValues.observe(getActivity(), userValues -> {
> if(userValues.data != null) {
> //update the UI
> }
> }
Should be
transactionViewModel = ViewModelProviders.of(getActivity(), providerFactory).get(TransactionViewModel.class);
// this goes in onViewCreated
viewModel.userValues.observe(viewLifecycleOwner, userValues -> {
if(userValues.data != null){
//update the ui
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论