我需要进行多个异步调用才能获取我需要填充recyclerview适配器的数据。对数据进行分页,因此必须获取第一页,然后使用该页面来获取下一页,依此类推,直到没有剩余页面或我得到一个空页面为止。为了获得每个页面的详细内容,我必须进行额外的网络调用。我该如何使用RxJava2 observables编写此代码,以便等待所有异步任务完成并最终获得可以传递给适配器的List。添加了带有回调的粗略示例代码。
private void showData() {
List<DataToDisplay> dataList = new ArrayList<>();
List<Page<ContentDescription>> pageList = getAllPagesWithContent();
for(Page<ContentDescription> page : pageList) {
page.getContentDescription().getItemData(new CallbackListener<ItemData>() {
@Override
public void onSuccess(ItemData itemData) {
itemData.getUsers.getLastUser(new CallbackListener<User>() {
@Override
public void onSuccess(User user) {
DataToDisplay dataToDisplay = new DataToDisplay();
dataToDisplay.setName(user.name());
dataToDisplay.setAddress(user.getAddress());
dataToDisplay.setImageUrl(user.getImageUrl());
dataList.add(dataToDisplay);
}
@Override
public void onError(Error error) {
error.printStackTrace();
}
});
}
@Override
public void onError(Error error) {
error.printStackTrace();
}
});
}
UserAdapter adapter = new UserAdapter(context, dataList);
userRecycler.setLayoutManager(new LinearLayoutManager(context));
userRecycler.setItemAnimator(new DefaultItemAnimator());
userRecycler.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
// Inside adapter
@Override
public void onBindViewHolder(@NonNull DataViewHolder holder, int position) {
DataToDisplay data = dataList.get(position);
holder.nameTextView1.setText(data.getName());
holder.addressTextView1.setText(data.getAddress());
...
}
private List<Page<ContentDescription>> getAllPagesWithContent() {
List<Page<ContentDescription>> allPagesList = new ArrayList<>();
dataManager.getFirstPage(new CallbackListener<Page<ContentDescription>>() {
@Override
public void onSuccess(Page<ContentDescription> firstPage) {
allPagesList.add(firstPage);
Page<ContentDescription> currentPage = firstPage;
while (currentPage != null && currentPage.hasNextPage()) {
Page<ContentDescription> nextPage = loadNextPage(currentPage);
if(nextPage != null) {
allPagesList.add(nextPage);
}
currentPage = nextPage;
}
}
@Override
public void onError(Error error) {
error.printStackTrace();
}
});
return allPagesList;
}
private Page<ContentDescription> loadNextPage(Page<ContentDescription> currentPage) {
currentPage.getNextPage(new CallbackListener<Page<ContentDescription>>() {
@Override
public void onSuccess(Page<ContentDescription> nextPage) {
return nextPage;
}
@Override
public void onError(Error error) {
error.printStackTrace();
return null;
}
});
}