2015-04-04 122 views
14

我想使用rxjava Observable在Retrofit中處理分頁。我遵循另一個question的建議。使用Retrofit時堆棧溢出rxjava concatWith

我有需要獲取100多頁,但連鎖失敗20頁左右,並在logcat的

04-04 04:12:11.766 2951-3012/com.example.app I/dalvikvm﹕ threadid=28: stack overflow on call to Ljava/util/concurrent/atomic/AtomicLongFieldUpdater$CASUpdater;.compareAndSet:ZLJJ 
04-04 04:12:11.766 2951-3012/com.example.app I/dalvikvm﹕ method requires 56+20+32=108 bytes, fp is 0x94b52350 (80 left) 
04-04 04:12:11.766 2951-3012/com.example.app I/dalvikvm﹕ expanding stack end (0x94b52300 to 0x94b52000) 
04-04 04:12:11.766 2951-3012/com.example.app I/dalvikvm﹕ Shrank stack (to 0x94b52300, curFrame is 0x94b548dc) 

是否有人知道爲什麼會停止任何進一步認購可觀察與下面的日誌可能發生?

更新:我知道這是由於遞歸,但有沒有更好的方式來處理分頁與retrofit和rxjava?

回答

23

所以,鑑於我回答了你引用的原始問題,我應該儘量回答這個問題。 :)

這是另一個有效的(也可能更簡單)替代我的原始分頁答案,現在我已經在我的阿森納開發了更多的Rx技巧。 :)(在java8拉姆達式僞碼完成):

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

終於可以這樣......想出了類似的方法,把它的工作:) – Bhuvan 2015-06-05 09:42:37

+3

真棒代碼!我想現在'Observable.range'也需要'int start'! – 2016-08-30 15:57:48

+0

假設我有1000頁是可行的/好嗎? – Ajinkya 2017-07-17 17:02:18