Search code examples
androidrx-javarx-java2rx-kotlin

Rxjava - Iterate the list with batch


i have a list of some strings, where i need to iterate the list in batch.
Example :

val list = ["a","b","c","d","e","f"]
Observable.fromIteratable(list)
          .map{
          //here i need to get 4 items at a time
          //like in first iteration i need to get ["a","b","c","d"]
          //in second iteration i need to get ["e","f"]
        }

Is there is any option to do perform this ?


Solution

  • User buffer

    periodically gather items emitted by an Observable into bundles and emit these bundles rather than emitting the items one at a time

     val list = arrayOf("1", "2", "3", "4", "5")
     Observable.fromIterable(list.asIterable())
         .buffer(4)
         .map { stringList: MutableList<String> ->
           println("insideMap -> $stringList")
           return@map "wow $stringList"
         }
         .subscribe { value: String -> println("OnResult $value")}
    
    //Output
    insideMap -> [1, 2, 3, 4]
    OnResult wow [1, 2, 3, 4]
    insideMap -> [5]
    OnResult wow [5]
    
    

    The Buffer operator transforms an Observable that emits items into an Observable that emits buffered collections of those items. There are a number of variants in the various language-specific implementations of Buffer that differ in how they choose which items go in which buffers.

    Note that if the source Observable issues an onError notification, Buffer will pass on this notification immediately without first emitting the buffer it is in the process of assembling, even if that buffer contains items that were emitted by the source Observable before it issued the error notification.