L
L
Lixo2019-02-01 07:12:19
Android
Lixo, 2019-02-01 07:12:19

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: [ 
            //массив объектов
           {
                ... //объект
            }
           ...
       ]
}

How to get all the data using RxJava, i.e. in this case, if in one request we get 10 objects ( limit=10 ) and there are 1000 of them (rowTotal: 1000), then we need to execute 100 requests sequentially, but in the background.
Now this is implemented inside AsyncTask and looks something like this:
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);

I want to rewrite using RxJava. Interested in the general concept or a link to an example.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
Z
z0rgoyok, 2019-02-03
@z0rgoyok

Observable.fromCallable {
    for (i in 1..10000) {
        load_4to_nado(i) 
    }
}

maybe something like this)

A
aol-nnov, 2019-02-01
@aol-nnov

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.

E
Eugene, 2019-02-01
@klim76

and exactly sequentially?
won't it fly?
Observable result
for(page = 0; page < total/lim; page++){
result.concat....(yuoyapi.apicall.(page))
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question