Search code examples
javakotlinreactor

Create Mono Array Object with keeping original ordering


I need to implement function that returns Mono< Array< ProcessedObject>>. As argument it takes list of objects and process them with function that returns Mono< ProcessedObject>. Function needs to keep original order, meaning first element on returned list must be created from first element from argument list. So far i have following solution but it doesn't keep required order. Is it even possible with Flux?

       private fun createItems(objects: List<Someobjects>): Mono<Array<ProcessedObject>> {
         return Flux.fromIterable(objects)
           .flatMap {
             processObject(it)
           }.collectList().map { it.toTypedArray() }
}

Edit: to clarify a little processObject returns Mono< ProcessedObject>


Solution

  • You can try with concatMap instead of flatMap.

    Here is a link for the Docu https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html#concatMap-java.util.function.Function-

    private fun createItems(objects: List<Someobjects>): Mono<Array<ProcessedObject> {
             return Flux.fromIterable(objects)
               .concatMap {
                 processObject(it)
               }.collectList().map { it.toTypedArray() }
    }
    

    The difference between flatMap and concatMap is that the later preserves the original order.