我是Android开发的新手,正在尝试使用一种良好的模式通过ViewModel,Retrofit,LiveData从Web服务访问我的数据。寻找有关此模式的反馈。
我经历了一些迭代和在线指南,并提出了这个
来自活动:
LiveData<TicklerResponse> ticklerLiveData =
ticklerViewModel.search(ticklerSearchObject);
ticklerLiveData.observe(this, new Observer<TicklerResponse>() {
@Override
public void onChanged(@Nullable TicklerResponse ticklerResponse) {
Log.d(TAG, "onChanged: ticklerResponse size = " + ticklerResponse.getContent().size());
}
});
ViewModel
public LiveData<TicklerResponse> search(TicklerSearchObject ticklerSearchObject) {
TicklerRepository ticklerRepository = TicklerRepository.getInstance();
String header = OscarOAuthContainer.getInstance()
.generateAuthorizationHeader(Verb.POST,"/tickler/search?startIndex=0&limit=1000");
MutableLiveData<TicklerResponse> liveData = new MutableLiveData<TicklerResponse>();
ticklerRepository.search(header,liveData, ticklerSearchObject);
return liveData;
}
存储库
public void search(final String authHeader, final MutableLiveData<TicklerResponse> ticklerLiveData, TicklerSearchObject ticklerSearchObj) {
Log.d(TAG, "search: called");
Call<TicklerResponse> call = api.search(authHeader,0,1000,ticklerSearchObj);
call.enqueue(new Callback<TicklerResponse>() {
@Override
public void onResponse(Call<TicklerResponse> call, Response<TicklerResponse> response) {
if(response.isSuccessful()){
Log.d(TAG, "onResponse: successful response for getProvider");
TicklerResponse result = response.body();
ticklerLiveData.setValue(result);
} else {
Log.d(TAG, "onResponse: NOT SUCCESSFUL");
}
}
@Override
public void onFailure(Call<TicklerResponse> call, Throwable t) {
t.printStackTrace();
}
});
}
这似乎可行,但是我担心在实例化/传递方法方面是否正确使用了LiveData结构。