Project Reactor’s buffer() groups elements from a Flux into lists, producing a new Flux of those lists. With buffer(3), each list contains at most three elements; a final list can be smaller. section 11.3.3
@Test
public void buffer() {
Flux<String> fruitFlux = Flux.just(
"apple", "orange", "banana", "kiwi", "strawberry");
Flux<List<String>> bufferedFlux = fruitFlux.buffer(3);
StepVerifier
.create(bufferedFlux)
.expectNext(Arrays.asList("apple", "orange", "banana"))
.expectNext(Arrays.asList("kiwi", "strawberry"))
.verifyComplete();
}
Five fruit names become two lists: the first contains three names, and the second contains the remaining two. StepVerifier checks both lists and completion. section 11.3.3
Buffering can also prepare chunks for parallel processing. Use flatMap() to turn each list back into a Flux, map its elements, and schedule each sub-Flux with subscribeOn(Schedulers.parallel()). Buffering alone does not make the work parallel. section 11.3.3
@Test
public void bufferAndFlatMap() throws Exception {
Flux.just(
"apple", "orange", "banana", "kiwi", "strawberry")
.buffer(3)
.flatMap(x ->
Flux.fromIterable(x)
.map(y -> y.toUpperCase())
.subscribeOn(Schedulers.parallel())
.log()
).subscribe();
}
This example uppercases the fruit names on parallel scheduler threads and uses log() to show Reactive Streams events. section 11.3.3
