How to convert Flux of DataBuffer to Mono of byte array in Project Reactor?

Viewed 6341

There is a Flux<DataBuffer>. What is the natural way of converting it to Mono<byte[]>?

Mono<byte[]> mergeDataBuffers(Flux<DataBuffer> flux){
  // ?
}
1 Answers

Use org.springframework.core.io.buffer.DataBufferUtils to join the DataBuffers from the Flux<DataBuffer> into a single DataBuffer, and then read that buffer into a byte array.


    Mono<byte[]> mergeDataBuffers(Flux<DataBuffer> dataBufferFlux) {
        return DataBufferUtils.join(dataBufferFlux)
                .map(dataBuffer -> {
                    byte[] bytes = new byte[dataBuffer.readableByteCount()];
                    dataBuffer.read(bytes);
                    DataBufferUtils.release(dataBuffer);
                    return bytes;
                });
    }

Be sure to take memory usage into consideration when doing so, since this approach will load all of the data into memory twice (once in the DataBuffers, and then again when copied into the byte[]).

Related