我正在使用一个简单的改装调用,该调用随后将更新数据,并且片段将通过视图模型对其进行观察。 不幸的是,由于某种原因,它根本不起作用。就像“ 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) {
....
}
});
}
MyViewModel:
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;
}
答案 0 :(得分:1)
您对Repository
MutableLiveData
发表了文章,但遵守了MyViewModel
LiveData
。合并它们或仅使用一个
尝试一下
MyViewModel:
public LiveData<List<MyObj>> fetchList(){
return repository.getList();
}
片段:
mViewModel.fetchList().observe(this, new Observer<List<MyObj>>(){...}