Answer the question
In order to leave comments, you need to log in
RxJava + Retrofit how to execute a series of sequential requests asynchronously?
There is a server api something like https://.../api/getData?limit=10&offset=0
We request data "page by page", as a result we get JSON
{
rowTotal: 1000, <--- общее количество данных
data: [
//массив объектов
{
... //объект
}
...
]
}
int page = 0;
int total = 0;
int offset = 0;
do {
offset = page * PAGE_SIZE;
TPResponse tpResponse = null;
try {
Response response = api.getByRange("api/all-data-by-range", offset, PAGE_SIZE).execute();
if (response.body() == null) {
break;
}
tpResponse = (TPResponse) response.body();
total = tpResponse.getTotalRecords();
if (tpResponse.getData() != null && !tpResponse.getData().isEmpty()) {
//передаем данные на обработку
dataArrivedListener.ModelsArrived(tpResponse.getData());
}
} catch (IOException e) {
Log.e("SYNC ERROR", String.valueOf(offset));
e.printStackTrace();
return;
}
page++;
//считаем процент загруженных данных
int totalPages = (int) Math.ceil((float) total / PAGE_SIZE);
publishProgress((int) ((page / (float) totalPages) * 100));
} while ((offset + PAGE_SIZE) < total);
Answer the question
In order to leave comments, you need to log in
Observable.fromCallable {
for (i in 1..10000) {
load_4to_nado(i)
}
}
it is not optimal to load all thousands of records per client.
The R in Rx stands for reactive.
reactive (English) - reactive; reactive;
Now think about how you should react. For example, you load 10, the user scrolls 5, you load (react) another 10, the user scrolls... well, the idea is clear, I think.
This is an incomparably more pleasant experience than seeing a spinner while all thousands are loaded or a twitching list from out-of-order asynchronous responses.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question