android - 未在 LiveData 收到数据更改
问题描述
我正在使用一个简单的改造调用,然后更新数据,片段通过视图模型对其进行观察。不幸的是,由于某种原因,它不起作用。就像“postValue 或 setValue”不起作用或干脆消失了。
分段:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewModel = ViewModelProviders.of(requireActivity()).get(MyViewModel.class);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
subscribe();
mViewModel.fetchList();
return rootView;
}
private void subscribe() {
mViewModel.getListObservable().observe(this, new Observer<List<MyObj>>() {
@Override
public void onChanged(@Nullable List<MyObj> objList) {
....
}
});
}
我的视图模型:
private LiveData<List<MyObj>> mListObservable = new MutableLiveData<>();
private Repository repository;
public MoviesViewModel(Application application) {
super(application);
repository = new Repository();
}
public void fetchList(){
mListObservable = repository.getList();
}
public LiveData<List<MovieObj>> getListObservable(){
return mListObservable;
}
存储库:
public LiveData<List<MyObj>> getList(){
final MutableLiveData<List<MovieObj>> data = new MutableLiveData<>();
mServiceInterface.getData("en-US").enqueue(new Callback<MyResponseCustom>() {
@Override
public void onResponse(Call<MyResponseCustom> call, Response<MyResponseCustom> response) {
data.postValue(response.body().getResult());
}
@Override
public void onFailure(Call<MyResponseCustom> call, Throwable t) {
}
});
return data;
}
解决方案
你很重视Repository
MutableLiveData
但观察MyViewModel
LiveData
。合并它们或仅使用一个
像这样试试
我的视图模型:
public LiveData<List<MyObj>> fetchList(){
return repository.getList();
}
分段:
mViewModel.fetchList().observe(this, new Observer<List<MyObj>>(){...}
推荐阅读
- linux - AT&T 32 位程序集在函数调用工作后会推送字符串吗?
- homebrew - 如何删除自制水龙头
- excel - 导入具有动态标题名称和动态列数的各种 CSV 文件
- amazon-web-services - Step 函数中 ECS 任务的输入和输出
- javascript - 如何使用 CSS 滤镜或 colorMatrix 将 VIBRANCE 效果应用于图像
- java - 如何使用 keytab 文件的输入流解析 Web 服务的 TGS
- javascript - 默认的 Date.toLocalDateString() 基于什么?
- angular - 在 Angular 8 中,我遇到了 Angular 中组件重叠的问题。标题组件是重叠的子组件?如何克服?
- autodesk-forge - 在 Autodesk Viewer 中打开 Excel 文件
- rest - 如何使用 RESTful API 到 Libpod 库请求具有特定构建选项的构建