Reputation: 33
We recently started to refactor our Spring WebMVC code to WebFlux, replacing RestTemplate's by WebClient.
From an external web server, we receive a flat list of objects (Product), each of which contains a reference to a parent object:
webClient
.get()
.uri(productURI)
.retrieve()
.bodyToFlux(Product.class)
We now to transform this list of products into a tree-like structure, consisting of few root Products (as a list) and many child Products in a hierarchical structure beneath each root Product.
In the former code, transformation was easily done, as we ended up with the complete flat list, from which we created a new result list.
With reactive streams, I'm puzzled how to transform the original Flux of Products into a completely different structure.
Upvotes: 2
Views: 620
Reputation: 335
There are multiple solutions available.
In case your data fits in memory, the response is not paginated and you want to keep the existing implementation, you can collect the Flux<Product>
into a list and use the existing algorithm.
productFlux
.collectList()
.map(products -> buildTree(products))
In case you want to compute the tree structure more efficiently, e.g. because of loading data in paginated manner, the reduce
operator would be the way to go.
productFlux
.reduce(new ProductTree(), (tree, nextProduct) -> tree.add(nextProduct))
Here the tree needs a method add(nextProduct)
to construct the final tree in multiple steps.
Upvotes: 3