Stack overflow when using Retrofit rxjava concatWith

前端 未结 1 754
花落未央
花落未央 2020-12-05 05:51

I want to handle pagination in Retrofit using rxjava Observable. I followed the advice from another question.

I have more than 100 pages that needs to be fetched, b

相关标签:
1条回答
  • 2020-12-05 06:23

    So, given I answered the original question you referenced I should probably try to answer this case as well. :)

    This is another valid (and potentially simpler) alternative to my original paging answer, now that I've developed a few more Rx tricks in my arsenal. :) (Done in java8 lambda-style pseudocode):

    Observable.range(Integer.MAX_VALUE)
        // Get each page in order.
        .concatMap(page -> getResults(page))
        // Take every result up to and including the one where the next page index is null.
        .takeUntil(result -> result.next == null)
        // Add each output to a list builder. I'm using Guava's ImmutableList, but you could
        // just as easily use a regular ArrayList and avoid having to map afterwards. I just
        // personally prefer outputting an immutable data structure, and using the builder
        // is natural for this.
        //
        // Also, if you wanted to have the observable stream the full output at each page,
        // you could use collect instead of reduce. Note it has a slightly different syntax. 
        .reduce(
            ImmutableList.<ResponseObject>builder(),
            (builder, response) -> builder.addAll(response.results))
        // Convert list builder to one List<ResponseObject> of all the things.
        .map(builder -> builder.build())
        .subscribe(results -> { /* Do something with results. */ });
    
    0 讨论(0)
提交回复
热议问题