我有这种方法
private void setNews(final GetDataCallback getDataCallback){
GetDataService service = RetrofitClientInstance.getRetrofitInstance().create(GetDataService.class);
Call<ItemsAPI> call = service.getAllItems();
call.enqueue(new Callback<ItemsAPI>() {
@Override
public void onResponse(Call<ItemsAPI> call, Response<ItemsAPI> response) {
if (response.isSuccessful()) {
Log.d(TAG, "onResponse");
items = response.body();
getDataCallback.onGetData(items.getItems());
}
else {
getDataCallback.onError();
}
}
@Override
public void onFailure(Call<ItemsAPI> call, Throwable t) {
getDataCallback.onError();
Log.d(TAG, "onFailure "+ t.getMessage());
}
});
}
我从API获取信息的地方 我需要将此信息提供给另一个呼叫球
public MutableLiveData<List<News>> getNews(){
setNews(new GetDataCallback() {
@Override
public void onGetData(List<News> newsData) {
dataSet = newsData;
Log.d(TAG, "size: "+dataSet.size());
}
@Override
public void onError() {
}
});
MutableLiveData<List<News>> data = new MutableLiveData<>();
Log.d(TAG, "size before setValue: "+dataSet.size());
data.setValue(dataSet);
return data;
}
当我查看日志时,我可以看到
2019-05-18 10:45:17.575 2250-2250/? D/NewsRepository: size before setValue: 0
2019-05-18 10:45:18.334 2250-2250/com.krasnov.rxjavalearning D/NewsRepository: onResponse
2019-05-18 10:45:18.334 2250-2250/com.krasnov.rxjavalearning D/NewsRepository: size: 30
从另一个类中,我调用getNews()方法。我需要先做setNews(),在数据集中有元素,然后再从getNews()返回值。
我该怎么做?
答案 0 :(得分:0)
Retrofit.enqueue()是异步调用,以后会执行。
如果要从getNews()的Livedata更新ui
LiveData<Data> getNews() {
final MutableLiveData<Data> data = new MutableLiveData<>();
setNews( new MyCallback(){
Void onSuccess(Data data){
data.setValue(data); // for success live data get call back
}
void onError(){
data.setValue(null); // for error case can pass null or empty list
}
});
return data;
}
您将获得响应的更新