我从我的片段中调用:
videoViewModel.fetchContentSections();
我从我的虚拟机打电话:
public void fetchContentSections(){repository.getContent();}
从我的仓库我这样做:
apiService.getContent(request).enqueue(new Callback<Content>() {
@Override
public void onResponse(Call<Content> call, Response<Content> response) {
List<Section> sections = response.body() != null ? response.body().getSections() : null;
if (sections != null && !sections.isEmpty()) {
final List<Section> sectionList = new ArrayList<>();
for (Section section : sections) {
sectionList.add(section);
}
}
}
@Override
public void onFailure(Call<Content> call, Throwable t) {
Log.d(TAG, "onFailure" + Thread.currentThread().getName());
}
});
返回数据,但在这种情况下列表为空。
如果我将 if 语句替换为:
sectionsMutableLiveList.postValue(response.body().getSections());
...一切正常。但是我需要使用一个非 LiveData 列表,这样我就可以将 sectionList 写入一个文件。我希望然后从文件中读取列表并将值发布到 LiveData 列表到我的虚拟机。
有人知道我做错了什么吗?
要从 Retrofit 以同步方式接收结果,您必须使用“执行”。
/**
* Synchronously send the request and return its response.
*
* @throws IOException if a problem occurred talking to the server.
* @throws RuntimeException (and subclasses) if an unexpected error occurs creating the request or
* decoding the response.
*/
Response<T> execute() throws IOException;
这允许您返回结果并将其写入文件。所以像这样:
try {
Response<Content> response = apiService.getContent(request).execute();
List<Section> sections = response.body() != null ? response.body().getSections() : null;
if (sections != null && !sections.isEmpty()) {
final List<Section> sectionList = new ArrayList<>();
for (Section section : sections) {
sectionList.add(section);
}
}
} catch(IOException) {
Log.d(TAG, "onFailure" + Thread.currentThread().getName());
}
问题是您随后在
MainThread
上执行调用,您的应用程序将冻结,直到调用完成。使用 enqueue
和回调,请求是异步执行的,您的 MainThread
不会被阻塞。