目前我使用一个服务与
retrofit
但我想更新这个模型
ViewModel
具有
LiveData
. 我正在努力的是如何设置
Repository
更新livedata对象。
在我看到的例子中,人们在存储库中返回一个LiveData包装的对象,如下所示
public LiveData<NewsResponse> getData(){
final MutableLiveData<DataResponse> data = new MutableLiveData<>();
apiService.getData().enqueue(new Callback<DataResponse>() {
@Override
public void onResponse(Call<DataResponse> call, Response<DataResponse> response){
if (response.isSuccessful()){
data.setValue(response.body());
}
}
@Override
public void onFailure(Call<DataResponse> call, Throwable t) {
data.setValue(null);
}
});
return data;
}
然后在
视图模型
他们会的
private MutableLiveData<DataResponse> dataResponse = new MutableLiveData();
private Repository repository;
public PopularGamesViewModel(@NonNull Application application) {
repository = new Repository();
dataResponse = repository.getData();
}
public MutableLiveData<DataResponse> getData(){
return dataResponse;
}
然后在
Activity
去他们想去的地方
viewModel.getData().observe(this, dataResponse -> {
if (dataResponse != null)
{
// Do something
}
});
在我看来,任何时候我想从存储库中获取新的/更新的数据
实时数据
对象的创建使以前的观察者不再工作,所以我还必须再次设置观察者对吗?
你怎么能把它设置成让你不断观察
实时数据
对象,然后从
视图模型
调用存储库以获取任何新数据,然后
视图模型
更新
实时数据
对象来自
存储库
?
我的建议有意义吗?