Search code examples
javaproject-reactorreactor

Split Flux into lists containing up to 20 elements in Reactor


I want to split Flux into multiple Lists (or sub-Fluxes) in a way that each one will contain up to 20 elements.

My Flux:

"a","s","x"...

converted to: List<String>, List<String> or Flux<String>, Flux<String> - each one with up to 20 elements.


Solution

  • It seems to me that Flux.window(20) returning Flux<Flux<T>> is what you are looking for. Check its reference documentation on which one can read:

    Split this Flux sequence into multiple Flux windows containing maxSize elements (or less for the final window) and starting from the first item. Each Flux window will onComplete after maxSize items have been routed.


    (Thanks @MichaelBerry for the hint)

    There is also Flux.buffer(20) which will return Flux<List<T>>. In the reference documentation we can read:

    Collect incoming values into multiple List buffers that will be emitted by the returned Flux each time the given max size is reached or once this Flux completes.